Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Remote MCP servers and OAuth

After this lesson: I can follow how an MCP client finds a remote server's sign-in and gets a token for it.

80 min lesson9 commandsAgent lab: write an AI agent loop with tools, with a stand-in model

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

How a remote MCP server knows the caller

A remote MCP server, such as one that reads your calendar, must know whose calendar to open. MCP uses OAuth 2.1, the same sign-in method behind "Sign in with" buttons, to give the client a token.

Getting this wrong hands your data to the wrong program. You will follow every step of a sign-in in the lab.

By the end of this lesson

Note

I can follow how an MCP client finds a remote server's sign-in and gets a token for it.

Key words

WordWhat it meansExample
Access tokena short-lived pass the client shows on each request
Authorization serverthe service that signs the person in and issues tokens
Resource servera server that accepts tokens, here the MCP server
Scopeone permission a token carriesnotes:read
Audiencethe server a token was made for
PKCEa secret check that stops a stolen code being used

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The server says where to sign in

Over HTTP, the MCP server is a resource server: it accepts tokens and never issues them. A request with no token gets 401 and a WWW-Authenticate header.

That header names the server's protected resource metadata. The metadata names the authorization server, and that server's own metadata gives the addresses to sign in and to get a token. A stdio server skips all this and reads its secrets from the environment.

From a 401 to a working token

sequenceDiagram
  participant C as Client
  participant M as MCP server
  participant A as Authorization server
  C->>M: POST /mcp, no token
  M-->>C: 401, resource_metadata and scope
  C->>M: GET protected resource metadata
  M-->>C: authorization_servers
  C->>A: GET authorization server metadata
  A-->>C: authorize and token addresses
  C->>A: sign in with code_challenge and resource
  A-->>C: code and iss
  C->>A: code, code_verifier and resource
  A-->>C: access token for this MCP server
  C->>M: POST /mcp, Bearer token

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

PKCE and the resource parameter

Before signing in, the client makes a secret verifier and sends only its hash, the challenge. To swap the code for a token it must show the verifier, so a stolen code is useless. MCP requires the S256 hash.

The client also sends resource, the MCP server's address. The token's audience is then that server, and the server refuses any token made for another.

Try it: make a PKCE challenge

Code: python
# PKCE: the client keeps a secret, the verifier, and sends only its hash, the challenge.
import base64
import hashlib

verifier = "lab-verifier-0123456789-abcdefghijklmnopqrstuvwxyz"
digest = hashlib.sha256(verifier.encode()).digest()
challenge = base64.urlsafe_b64encode(digest).decode().rstrip("=")
print("challenge:", challenge)

# Change one letter of the verifier. Does the challenge change a little or completely?

Make a free account to save your work and track your progress.

Worked example: getting a client_id

WayWhat happensWhen
Pre-registeredThe client was set up with this authorization server in advanceA known pair of client and server
Client ID metadata documentThe client_id is an HTTPS address of a JSON file about the clientThe preferred way for a new pair
Dynamic registrationThe client posts to /register and gets an id backDeprecated since 2026-07-28, kept for old servers

The cells students fill in are left blank in this preview.

Write the two pretend servers, part 1

Command
docker exec tools sh -c "mkdir -p mcp && printf '%s\n' '\"\"\"A pretend authorization server and an MCP server that takes only tokens made for it.\"\"\"' 'import base64' 'import hashlib' 'import hmac' 'import json' 'import threading' 'from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer' 'from urllib.parse import parse_qs, urlparse' 'AS = \"http://127.0.0.1:8770\"' 'MCP = \"http://127.0.0.1:8771/mcp\"' 'META = \"http://127.0.0.1:8771/.well-known/oauth-protected-resource/mcp\"' 'KEY = b\"lab-key\"' 'CODES = {}' 'def b64(raw):' '    return base64.urlsafe_b64encode(raw).decode().rstrip(\"=\")' '' '' 'def q(text):' '    return chr(34) + text + chr(34)' '' '' 'def sign(claims):' '    body = b64(json.dumps(claims).encode())' '    return body + \".\" + b64(hmac.new(KEY, body.encode(), \"sha256\").digest())' '' '' 'def check(token):' '    body, mac = (token + \".\").split(\".\")[:2]' > mcp/auth.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the two pretend servers, part 2

Command
docker exec tools sh -c "printf '%s\n' '    if not hmac.compare_digest(mac, b64(hmac.new(KEY, body.encode(), \"sha256\").digest())):' '        return None' '    return json.loads(base64.urlsafe_b64decode(body + \"==\"))' 'class Base(BaseHTTPRequestHandler):' '    def log_message(self, *args):' '        pass' '' '    def send(self, status, value, header=None):' '        text = json.dumps(value).encode()' '        self.send_response(status)' '        self.send_header(\"Content-Type\", \"application/json\")' '        if header:' '            self.send_header(\"WWW-Authenticate\", header)' '        self.send_header(\"Content-Length\", str(len(text)))' '        self.end_headers()' '        self.wfile.write(text)' 'class Authorization(Base):' '    def do_GET(self):' '        url = urlparse(self.path)' '        ask = {k: v[0] for k, v in parse_qs(url.query).items()}' '        if url.path == \"/.well-known/oauth-authorization-server\":' >> mcp/auth.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the two pretend servers, part 3

Command
docker exec tools sh -c "printf '%s\n' '            return self.send(200, {\"issuer\": AS, \"authorization_endpoint\": AS + \"/authorize\",' '                                   \"token_endpoint\": AS + \"/token\", \"code_challenge_methods_supported\": [\"S256\"],' '                                   \"client_id_metadata_document_supported\": True})' '        # The person signs in and agrees here. In the lab they agree at once.' '        CODES[\"c-1\"] = ask' '        self.send(200, {\"code\": \"c-1\", \"iss\": AS})' '    def do_POST(self):' '        size = int(self.headers[\"Content-Length\"])' '        form = {k: v[0] for k, v in parse_qs(self.rfile.read(size).decode()).items()}' '        asked = CODES.pop(form[\"code\"], None)' '        if not asked or not b64(hashlib.sha256(form[\"code_verifier\"].encode()).digest()) == asked[\"code_challenge\"]:' '            return self.send(400, {\"error\": \"invalid_grant\"})' >> mcp/auth.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the two pretend servers, part 4

Command
docker exec tools sh -c "printf '%s\n' '        token = sign({\"iss\": AS, \"aud\": form[\"resource\"], \"scope\": asked[\"scope\"]})' '        self.send(200, {\"access_token\": token, \"token_type\": \"Bearer\"})' 'class Server(Base):' '    def do_GET(self):' '        self.send(200, {\"resource\": MCP, \"authorization_servers\": [AS], \"scopes_supported\": [\"notes:read\"]})' '' '    def do_POST(self):' '        msg = json.loads(self.rfile.read(int(self.headers[\"Content-Length\"])))' '        claims = check(self.headers.get(\"Authorization\", \"\")[7:])' '        if not claims or not claims[\"aud\"] == MCP:' '            return self.send(401, {}, \"Bearer resource_metadata=\" + q(META) + \", scope=\" + q(\"notes:read\"))' '        need = \"notes:write\" if msg[\"params\"][\"name\"] == \"add_note\" else \"notes:read\"' '        if need not in claims[\"scope\"].split():' >> mcp/auth.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the two pretend servers, part 5

Command
docker exec tools sh -c "printf '%s\n' '            return self.send(403, {}, \"Bearer error=\" + q(\"insufficient_scope\") + \", scope=\" + q(need)' '                             + \", resource_metadata=\" + q(META))' '        done = {\"resultType\": \"complete\", \"content\": [{\"type\": \"text\", \"text\": \"Notes: buy milk\"}]}' '        self.send(200, {\"jsonrpc\": \"2.0\", \"id\": msg[\"id\"], \"result\": done})' 'def start():' '    for port, kind in [(8770, Authorization), (8771, Server)]:' '        server = ThreadingHTTPServer((\"127.0.0.1\", port), kind)' '        threading.Thread(target=server.serve_forever, daemon=True).start()' >> mcp/auth.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the client, part 1

Command
docker exec tools sh -c "mkdir -p mcp && printf '%s\n' '\"\"\"An MCP client that finds out how to sign in from the server, then calls it with a token.\"\"\"' 'import base64' 'import hashlib' 'import json' 'import urllib.request' 'from urllib.error import HTTPError' 'from urllib.parse import urlencode' 'import auth' 'auth.start()' 'def http(url, body=None, token=None):' '    request = urllib.request.Request(url, body, {\"Content-Type\": \"application/json\"})' '    if token:' '        request.add_header(\"Authorization\", \"Bearer \" + token)' '    try:' '        answer = urllib.request.urlopen(request)' '    except HTTPError as refused:' '        answer = refused' '    return answer.status, answer.headers.get(\"WWW-Authenticate\"), json.loads(answer.read() or \"{}\")' '' '' 'def call(tool, token):' '    msg = {\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"tools/call\", \"params\": {\"name\": tool, \"arguments\": {}}}' > mcp/authclient.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the client, part 2

Command
docker exec tools sh -c "printf '%s\n' '    return http(auth.MCP, json.dumps(msg).encode(), token)' 'status, header, _ = call(\"read_notes\", None)' 'print(\"1. no token:\", status, header)' 'where = header.split(chr(34))[1]' 'found = http(where)[2]' 'print(\"2. protected resource metadata:\", found)' 'server = http(found[\"authorization_servers\"][0] + \"/.well-known/oauth-authorization-server\")[2]' 'print(\"3. authorization server:\", server[\"authorization_endpoint\"], server[\"code_challenge_methods_supported\"])' 'verifier = \"lab-verifier-0123456789-abcdefghijklmnopqrstuvwxyz\"' 'challenge = auth.b64(hashlib.sha256(verifier.encode()).digest())' 'print(\"4. PKCE challenge:\", challenge)' 'ask = {\"client_id\": \"https://app.example/client.json\", \"response_type\": \"code\", \"code_challenge\": challenge,' '       \"code_challenge_method\": \"S256\", \"resource\": auth.MCP, \"scope\": found[\"scopes_supported\"][0]}' >> mcp/authclient.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the client, part 3

Command
docker exec tools sh -c "printf '%s\n' 'code = http(server[\"authorization_endpoint\"] + \"?\" + urlencode(ask))[2]' 'print(\"5. code:\", code[\"code\"], \"issuer matches:\", code[\"iss\"] == server[\"issuer\"])' 'form = urlencode({\"grant_type\": \"authorization_code\", \"code\": code[\"code\"],' '                  \"code_verifier\": verifier, \"resource\": auth.MCP}).encode()' 'token = http(server[\"token_endpoint\"], form)[2][\"access_token\"]' 'print(\"6. token claims:\", auth.check(token))' 'print(\"7. read_notes:\", call(\"read_notes\", token)[2][\"result\"][\"content\"][0][\"text\"])' 'status, header, _ = call(\"add_note\", token)' 'print(\"8. add_note:\", status, header)' 'other = auth.sign({\"iss\": auth.AS, \"aud\": \"http://127.0.0.1:9999/mcp\", \"scope\": \"notes:read\"})' 'print(\"9. a token made for another server:\", call(\"read_notes\", other)[0])' >> mcp/authclient.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Sign in and call the server

Command
docker exec tools python3 mcp/authclient.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What authclient.py printed

StepWhat it showed
1 No token401, resource_metadata=".../.well-known/oauth-protected-resource/mcp", scope="notes:read"
2 and 3 Metadataauthorization_servers http://127.0.0.1:8770, then its /authorize address and S256
4 PKCEchallenge f8CeL99LeWgV7b9hELnDCgYY9kq7E0aCtLTyx4OQ1NM
5 Sign incode c-1, issuer matches: True
6 Tokenaud http://127.0.0.1:8771/mcp, scope notes:read
7 read_notesNotes: buy milk
8 add_note403, error="insufficient_scope", scope="notes:write"
9 Token for another server401

The cells students fill in are left blank in this preview.

Check the Run

Have a go

Check the Run

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A common mistake

Warning

Many people think an MCP server may pass the token it received on to another service. It must not. A token is for one audience, so a server that calls another service gets its own token for it. Passing tokens on lets a stolen one open everything.

Match each part to its job

Have a go

Loading…

Your answers are marked here and are not kept. An account keeps your marks.

Assignment: read and check tokens

Write three pieces of an MCP sign-in.

parse_challenge(header) turns a WWW-Authenticate header into a dictionary of its parameters. pkce_challenge(verifier) returns the S256 challenge in URL-safe base64 with no padding. decide(claims, resource, needed) returns 401, 403 or 200 by the rules in the starter.

Code: python
import base64
import hashlib


def parse_challenge(header):
    # A WWW-Authenticate header such as:
    #   Bearer resource_metadata="https://a.example/x", scope="notes:read"
    # Return a dictionary of its parameters with the quote marks removed.
    return {}


def pkce_challenge(verifier):
    # SHA-256 of the verifier, in URL-safe base64, with the "=" padding removed.
    return verifier


def decide(claims, resource, needed):
    # claims: a dictionary from a checked token, or None if the check failed.
    # Return 401 if claims is None or claims["aud"] is not resource,
    # 403 if needed is not one of the space-separated words in claims["scope"],
    # otherwise 200.
    return 200

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.