Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Worked example · 25 min · revision 3

Remote Deployment with OAuth Authorization

Serve an MCP server over Streamable HTTP as an OAuth 2.1 resource server: publish RFC 9728 protected resource metadata, answer 401 with a resource_metadata pointer, accept only tokens whose audience is this server, return 403 insufficient_scope for missing scopes, check Origin, and never pass tokens through; then repeat the checks by hand with negative tests.

Contentsand lesson path

What you will learn

  • Deploy a remote server over Streamable HTTP that publishes protected resource metadata and accepts only access tokens issued for its own audience.

Prerequisites: MCP Fundamentals

01. Why it matters

A stdio server runs locally and reads credentials from its environment. Anyone who can reach a remote server's URL can send it requests, and its tools may change shared data. Authorization is optional in MCP 2026-07-28; HTTP servers that use it should follow the specification, and stdio servers should not.

In that design your MCP server is an OAuth 2.1 resource server. It never shows a login page and never issues tokens; an authorization server (your identity provider) does that. The server's jobs are narrow and strict:

  • tell clients where to get a token, by publishing Protected Resource Metadata (RFC 9728);
  • check every request's bearer token: signature, issuer, expiry, and an audience that is this server;
  • refuse a valid token that lacks a needed scope with 403 insufficient_scope, so the client can ask for more;
  • never forward the token it received to another service.

02. How a client finds its way in

A compliant client's first call goes like this. Your server takes part in steps 1, 2, 6 and 7 only.

  1. The client POSTs to the MCP endpoint without a token. The server answers 401 with WWW-Authenticate: Bearer resource_metadata="<metadata URL>", and preferably a scope parameter naming the scopes the request needs.
  2. The client fetches the metadata document. It names the resource (the canonical URL of the server), the authorization_servers that issue tokens for it, and scopes_supported. RFC 9728 requires resource to match the URL the client was calling; if it does not, the client must ignore the document.
  3. The client fetches the authorization server's own metadata (RFC 8414, or OpenID Connect discovery) and checks that its issuer exactly matches the identifier it started from.
  4. The client gets a client ID: a pre-registered one, a Client ID Metadata Document (an HTTPS URL used as the client ID, now the recommended option), or Dynamic Client Registration, which revision 2026-07-28 deprecates.
  5. The user signs in through the authorization code flow with PKCE (S256). The client sends the resource parameter (RFC 8707) with the server's canonical URL in both the authorization and the token request, so the token is issued for this server only. Since 2026-07-28 the client also checks any iss in the authorization response against that issuer (RFC 9207).
  6. The client sends Authorization: Bearer <token> on every request, never in the query string. The server validates it each time.
  7. If a later call needs more, the server answers 403 with error="insufficient_scope", the scopes the operation needs and resource_metadata. The client asks the user again for the union of its old and new scopes.

03. The worked example: setup

You will run a tracker server at http://127.0.0.1:8090/mcp with a read tool and a write tool. In a folder remote-lab, use the virtual environment from lesson 1: mcp==2.3.0 also installs pyjwt, cryptography and uvicorn.

Two small lab-only scripts stand in for an identity provider. mock_as.py publishes authorization server metadata and a signing key set (JWKS) on port 9000. mint.py signs a token as if a user had just finished the OAuth flow, with whatever audience and scopes you ask for. Real deployments use your provider and never write keys to disk.

Python · remote-lab/mock_as.py (lab only)
"""LAB ONLY: a stand-in authorization server that publishes metadata and keys.

It signs tokens with a fresh RSA key and never logs anyone in; mint.py plays
the part of a finished OAuth flow. Needs `cryptography` and `pyjwt`, both
installed with mcp 2.x.
"""
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from jwt.algorithms import RSAAlgorithm

ISSUER = "http://127.0.0.1:9000/lab"  # an issuer with a path, like most IdPs
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
with open("lab-as-key.pem", "wb") as f:  # read by mint.py; never do this for real
    f.write(key.private_bytes(serialization.Encoding.PEM,
                              serialization.PrivateFormat.PKCS8,
                              serialization.NoEncryption()))
JWK = json.loads(RSAAlgorithm.to_jwk(key.public_key())) | {"kid": "lab-1",
                                                          "use": "sig",
                                                          "alg": "RS256"}
METADATA = {
    "issuer": ISSUER,
    "authorization_endpoint": f"{ISSUER}/authorize",
    "token_endpoint": f"{ISSUER}/token",
    "jwks_uri": f"{ISSUER}/jwks.json",
    "code_challenge_methods_supported": ["S256"],
    "client_id_metadata_document_supported": True,
}


class Handler(BaseHTTPRequestHandler):
    def do_GET(self) -> None:
        body = {"/.well-known/oauth-authorization-server/lab": METADATA,
                "/lab/jwks.json": {"keys": [JWK]}}.get(self.path)
        data = json.dumps(body or {"error": "not_found"}).encode()
        self.send_response(200 if body else 404)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args: object) -> None:
        pass


if __name__ == "__main__":
    print(f"mock authorization server, issuer {ISSUER}", flush=True)
    ThreadingHTTPServer(("127.0.0.1", 9000), Handler).serve_forever()
Python · remote-lab/mint.py (lab only)
"""LAB ONLY: sign an access token as if the OAuth flow had just finished.

python mint.py <audience> "<scopes>" [--issuer URL] [--expired]
"""
import sys
import time

import jwt

args = sys.argv[1:]
issuer = args[args.index("--issuer") + 1] if "--issuer" in args else \
    "http://127.0.0.1:9000/lab"
now = int(time.time())
claims = {
    "iss": issuer, "aud": args[0], "sub": "user-42", "client_id": "lab-client",
    "scope": args[1], "iat": now,
    "exp": now - 60 if "--expired" in args else now + 600,
}
with open("lab-as-key.pem", "rb") as f:
    print(jwt.encode(claims, f.read(), algorithm="RS256", headers={"kid": "lab-1"}))

04. Step 1: The server

Python · remote-lab/remote_server.py
"""Remote tracker MCP server: Streamable HTTP behind OAuth (mcp 2.x SDK)."""
import json
import logging

import anyio
import jwt
from pydantic import AnyHttpUrl

from mcp.server import MCPServer
from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.auth.provider import AccessToken, TokenVerifier
from mcp.server.auth.settings import AuthSettings
from mcp.server.mcpserver.exceptions import ToolError
from mcp.server.transport_security import TransportSecuritySettings

ISSUER = "http://127.0.0.1:9000/lab"  # your authorization server
RESOURCE = "http://127.0.0.1:8090/mcp"  # the exact URL clients connect to
METADATA_URL = "http://127.0.0.1:8090/.well-known/oauth-protected-resource/mcp"
WRITE_TOOLS = {"close_issue"}
log = logging.getLogger("remote")


class JwtVerifier(TokenVerifier):
    """Accept only RS256 tokens from ISSUER whose audience is this server."""

    def __init__(self) -> None:
        self.keys = jwt.PyJWKClient(f"{ISSUER}/jwks.json", cache_keys=True)

    async def verify_token(self, token: str) -> AccessToken | None:
        try:  # the key fetch is blocking I/O, so keep it off the event loop
            key = await anyio.to_thread.run_sync(
                self.keys.get_signing_key_from_jwt, token)
            claims = jwt.decode(token, key.key, algorithms=["RS256"],
                                audience=RESOURCE, issuer=ISSUER,
                                options={"require": ["exp", "aud", "iss"]})
        except jwt.PyJWTError as exc:
            log.warning("token rejected: %s", type(exc).__name__)  # no token text
            return None
        return AccessToken(token=token, client_id=claims.get("client_id", "?"),
                           scopes=claims.get("scope", "").split(),
                           expires_at=claims["exp"], resource=RESOURCE,
                           subject=claims.get("sub"))


verifier = JwtVerifier()
mcp = MCPServer(
    "tracker-remote", version="0.5.0", token_verifier=verifier,
    auth=AuthSettings(issuer_url=AnyHttpUrl(ISSUER),
                      resource_server_url=AnyHttpUrl(RESOURCE),
                      required_scopes=["issues:read"],
                      validate_token_resource=True))
ISSUES = {101: "Login fails with SSO", 102: "Export drops accents"}


@mcp.tool()
def get_issue(number: int) -> dict[str, str | int]:
    """Read one issue by number."""
    if number not in ISSUES:
        raise ToolError(f"No issue #{number}.")
    return {"number": number, "title": ISSUES[number]}


@mcp.tool()
def close_issue(number: int) -> str:
    """Close one issue. Needs the issues:write scope."""
    token = get_access_token()  # backstop: the gate below should stop it first
    if token is None or "issues:write" not in token.scopes:
        raise ToolError("This token lacks the issues:write scope.")
    if number not in ISSUES:
        raise ToolError(f"No issue #{number}.")
    return f"Closed #{number}."


def classify(body: bytes) -> str:
    """Return "write", "other" or "bad", from the JSON-RPC body the SDK will run.

    Never decide from the Mcp-Name header: clients may Base64-encode it
    (=?base64?...?=), and hosts on 2025-11-25 or earlier do not send it.
    """
    try:
        msg = json.loads(body)
    except (ValueError, RecursionError):  # not JSON, or nested too deeply
        return "bad"
    if not isinstance(msg, dict):  # one message per POST: no batches
        return "bad"
    if msg.get("method") != "tools/call":
        return "other"
    params = msg.get("params")
    if not isinstance(params, dict) or not isinstance(params.get("name"), str):
        return "bad"
    return "write" if params["name"] in WRITE_TOOLS else "other"


class WriteScopeGate:
    """Answer 403 insufficient_scope before a write tool runs without the scope."""

    def __init__(self, app, max_body: int = 4 * 1024 * 1024) -> None:
        self.app, self.max_body = app, max_body

    async def __call__(self, scope, receive, send) -> None:
        if scope["type"] != "http" or scope["method"] != "POST":
            await self.app(scope, receive, send)
            return
        body = b""
        while True:  # read the whole body once, then hand it on unchanged
            message = await receive()
            if message["type"] == "http.disconnect":
                return
            body += message.get("body", b"")
            if len(body) > self.max_body:
                await self.reply(send, 413, None, b'{"error": "too large"}')
                return
            if not message.get("more_body"):
                break
        kind = classify(body)
        if kind == "bad":  # answer cleanly; never forward what we cannot read
            await self.reply(send, 400, None, json.dumps({
                "jsonrpc": "2.0",
                "error": {"code": -32600, "message": "Invalid Request"}}).encode())
            return
        if kind == "write":
            headers = dict(scope.get("headers") or [])
            auth = headers.get(b"authorization", b"").decode()
            token = auth[7:] if auth.lower().startswith("bearer ") else ""
            info = await verifier.verify_token(token) if token else None
            if info and "issues:write" not in info.scopes:
                challenge = ('Bearer error="insufficient_scope", '
                             'scope="issues:read issues:write", '
                             f'resource_metadata="{METADATA_URL}"')
                await self.reply(send, 403, challenge,
                                 b'{"error": "insufficient_scope"}')
                return
        sent = False

        async def replay():
            nonlocal sent
            if not sent:
                sent = True
                return {"type": "http.request", "body": body, "more_body": False}
            return await receive()

        await self.app(scope, replay, send)  # no or bad token: the SDK says 401

    @staticmethod
    async def reply(send, status: int, challenge: str | None, body: bytes) -> None:
        headers = [(b"content-type", b"application/json")]
        if challenge:
            headers.append((b"www-authenticate", challenge.encode()))
        await send({"type": "http.response.start", "status": status,
                    "headers": headers})
        await send({"type": "http.response.body", "body": body})


app = WriteScopeGate(mcp.streamable_http_app(
    transport_security=TransportSecuritySettings(
        allowed_hosts=["127.0.0.1:8090", "localhost:8090"],
        allowed_origins=["http://127.0.0.1:8090", "http://localhost:8090"])))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8090, log_level="warning")

How the pieces fit:

  • JwtVerifier is the whole token check. It fetches the signing key named by the token's kid (cached, and off the event loop), then lets jwt.decode verify the signature with the algorithm pinned to RS256, the issuer, the expiry and the audience, which must equal RESOURCE. Any failure returns None, and it logs the error type, never the token.
  • AuthSettings turns on the SDK's resource-server behaviour. It serves the metadata document at /.well-known/oauth-protected-resource/mcp, answers requests without a valid token with 401 and a resource_metadata pointer, requires issues:read on every request (403 otherwise), and with validate_token_resource=True refuses tokens whose resource is not resource_server_url.
  • WriteScopeGate adds a per-tool rule that the SDK does not provide: calling close_issue needs issues:write, and a token without it gets a 403 that lists every scope the call needs. It decides from the JSON-RPC body, the message the SDK will actually dispatch. It must not decide from the Mcp-Name header: clients may send that header Base64-encoded as =?base64?...?=, so a gate comparing the raw header can be bypassed with a read-only token; and hosts on 2025-11-25 or earlier send no Mcp-Name at all, yet the SDK still serves them. A body the gate cannot read as one JSON-RPC request gets a clean 400 instead of being passed on. close_issue also checks the scope itself through get_access_token(), as a second line of defence.
  • TransportSecuritySettings allowlists the Host and Origin headers. Streamable HTTP servers must validate Origin against DNS rebinding; list your real hostname, or every request is refused.
  • Stateless by design. Revision 2026-07-28 has no protocol sessions: every request carries its version and capabilities, so any replica behind a load balancer can serve any request. The SDK also serves hosts on 2025-11-25 and earlier through the old initialize handshake.

05. Step 2: Run it and probe every rule

Terminal · inside remote-lab, with the virtual environment active
python mock_as.py &
python remote_server.py 2>server.err &
for i in $(seq 90); do   # wait until both servers answer, up to 90 s
  curl -s -o /dev/null http://127.0.0.1:9000/ &&
    curl -s -o /dev/null http://127.0.0.1:8090/mcp && break
  sleep 1
done
curl -s -o /dev/null http://127.0.0.1:8090/mcp || echo "not up: read server.err"

post.py sends one 2026-07-28 request with the headers Streamable HTTP requires (MCP-Protocol-Version, Mcp-Method, Mcp-Name, an Accept listing JSON and event streams) and prints the status, any challenge, and the result.

Python · remote-lab/post.py
"""Send one MCP 2026-07-28 request over Streamable HTTP and show the reply.

python post.py <method> [name] [json-arguments] [--token T] [--origin O]
                [--b64-name]   (send Mcp-Name in the spec's Base64 form)
"""
import base64
import json
import sys
import textwrap
import urllib.error
import urllib.request

URL = "http://127.0.0.1:8090/mcp"


def show(text: str) -> None:
    print(textwrap.fill(text, 80, subsequent_indent="    ",
                        break_long_words=False, break_on_hyphens=False))


args = sys.argv[1:]
options = {k: args[args.index(k) + 1] for k in ("--token", "--origin") if k in args}
b64_name = "--b64-name" in args
args = [a for a in args if a not in options and a not in options.values()
        and a != "--b64-name"]
method = args[0]
params = {"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
                    "io.modelcontextprotocol/clientCapabilities": {}}}
headers = {"Content-Type": "application/json", "MCP-Protocol-Version": "2026-07-28",
           "Accept": "application/json, text/event-stream", "Mcp-Method": method}
if len(args) > 1:
    params |= {"name": args[1], "arguments": json.loads(args[2])}
    headers["Mcp-Name"] = args[1]
    if b64_name:  # the encoding the spec defines for unsafe or unusual names
        encoded = base64.b64encode(args[1].encode()).decode()
        headers["Mcp-Name"] = f"=?base64?{encoded}?="
if "--token" in options:
    headers["Authorization"] = f"Bearer {options['--token']}"
if "--origin" in options:
    headers["Origin"] = options["--origin"]
body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
req = urllib.request.Request(URL, body.encode(), headers, method="POST")
try:
    resp = urllib.request.urlopen(req, timeout=10)
except urllib.error.HTTPError as err:
    resp = err

show(f"HTTP {resp.status}")
if resp.headers.get("WWW-Authenticate"):
    show("WWW-Authenticate: " + resp.headers["WWW-Authenticate"])
text = resp.read().decode()
for line in text.splitlines():  # an SSE reply carries the JSON on a data: line
    if line.startswith("data:"):
        text = line[5:]
try:
    reply = json.loads(text)
except ValueError:
    show(f"body: {text}")
else:
    result = reply.get("result", {})
    if "error" in reply:
        show(f"error: {json.dumps(reply['error'])}")
    elif "structuredContent" in result:
        show(f"structuredContent: {json.dumps(result['structuredContent'])}")
    else:
        show(f"body: {json.dumps(reply)}")
Terminal · no token, then the metadata document
python post.py tools/list
curl -s http://127.0.0.1:8090/.well-known/oauth-protected-resource/mcp \
  | python -m json.tool
Expected output
HTTP 401
WWW-Authenticate: Bearer error="invalid_token",
    error_description="Authentication required",
    resource_metadata="http://127.0.0.1:8090/.well-known/oauth-protected-resource/mcp"
error: "invalid_token"
{
    "resource": "http://127.0.0.1:8090/mcp",
    "authorization_servers": [
        "http://127.0.0.1:9000/lab"
    ],
    "scopes_supported": [
        "issues:read"
    ],
    "bearer_methods_supported": [
        "header"
    ]
}

That is steps 1 and 2 of the flow: the challenge points at the metadata, and the metadata names the authorization server. The SDK's 401 has no scope parameter, so clients fall back to scopes_supported. Now mint tokens with different audiences and scopes and try each rule:

Terminal · or save as probes.sh and run bash probes.sh
READ=$(python mint.py http://127.0.0.1:8090/mcp "issues:read")
WRITE=$(python mint.py http://127.0.0.1:8090/mcp "issues:read issues:write")
OTHER=$(python mint.py https://api.other.example "issues:read issues:write")
OLD=$(python mint.py http://127.0.0.1:8090/mcp "issues:read" --expired)
echo "== token for another API";   python post.py tools/list --token "$OTHER"
echo "== expired token";           python post.py tools/list --token "$OLD"
echo "== read token, read tool"
python post.py tools/call get_issue '{"number": 101}' --token "$READ"
echo "== read token, write tool"
python post.py tools/call close_issue '{"number": 101}' --token "$READ"
echo "== read token, write tool, Mcp-Name sent as =?base64?...?="
python post.py tools/call close_issue '{"number": 101}' --token "$READ" --b64-name
echo "== write token, write tool"
python post.py tools/call close_issue '{"number": 101}' --token "$WRITE"
echo "== foreign Origin"
python post.py tools/list --token "$READ" --origin https://evil.example
Expected output
== token for another API
HTTP 401
WWW-Authenticate: Bearer error="invalid_token",
    error_description="Authentication required",
    resource_metadata="http://127.0.0.1:8090/.well-known/oauth-protected-resource/mcp"
error: "invalid_token"
== expired token
HTTP 401
WWW-Authenticate: Bearer error="invalid_token",
    error_description="Authentication required",
    resource_metadata="http://127.0.0.1:8090/.well-known/oauth-protected-resource/mcp"
error: "invalid_token"
== read token, read tool
HTTP 200
structuredContent: {"number": 101, "title": "Login fails with SSO"}
== read token, write tool
HTTP 403
WWW-Authenticate: Bearer error="insufficient_scope", scope="issues:read
    issues:write",
    resource_metadata="http://127.0.0.1:8090/.well-known/oauth-protected-resource/mcp"
error: "insufficient_scope"
== read token, write tool, Mcp-Name sent as =?base64?...?=
HTTP 403
WWW-Authenticate: Bearer error="insufficient_scope", scope="issues:read
    issues:write",
    resource_metadata="http://127.0.0.1:8090/.well-known/oauth-protected-resource/mcp"
error: "insufficient_scope"
== write token, write tool
HTTP 200
structuredContent: {"result": "Closed #101."}
== foreign Origin
HTTP 403
body: Invalid Origin header

The token for another API is genuine, signed by the trusted issuer and current, yet refused: its audience is not this server. That check stops a token for one service being replayed against another. The Base64 probe sends Mcp-Name: =?base64?Y2xvc2VfaXNzdWU=?=, a legal encoding of close_issue that a gate comparing the raw header lets through. server.err records why each token failed (InvalidAudienceError, ExpiredSignatureError) without recording the tokens.

The gate must also fail cleanly on input it cannot read: each malformed request from odd_bodies.py must get a 400 JSON-RPC error, never a 500. Stop both servers afterwards with kill %1 %2.

Python · remote-lab/odd_bodies.py
"""Send malformed bodies to the gate; each must get a clean 400, never a 500.

python odd_bodies.py <token>
"""
import json
import sys
import urllib.error
import urllib.request

HEADERS = {"Content-Type": "application/json", "MCP-Protocol-Version": "2026-07-28",
           "Accept": "application/json, text/event-stream",
           "Mcp-Method": "tools/call", "Mcp-Name": "close_issue",
           "Authorization": f"Bearer {sys.argv[1]}"}
CALL = {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": {"name": ["close_issue"], "arguments": {"number": 101}}}
BODIES = {
    "name is a list": json.dumps(CALL),
    "batch of one call": json.dumps([CALL]),
    "100,000 nested arrays": "[" * 100_000 + "]" * 100_000,
    "not JSON": "{oops",
}
for label, body in BODIES.items():
    req = urllib.request.Request("http://127.0.0.1:8090/mcp", body.encode(), HEADERS)
    try:
        resp = urllib.request.urlopen(req, timeout=10)
    except urllib.error.HTTPError as err:
        resp = err
    error = json.loads(resp.read() or b"{}").get("error", {})
    print(f"{label:<22} HTTP {resp.status} {error.get('code', '')}")
Terminal
python odd_bodies.py "$READ"
Expected output
name is a list         HTTP 400 -32600
batch of one call      HTTP 400 -32600
100,000 nested arrays  HTTP 400 -32600
not JSON               HTTP 400 -32600

06. Calling upstream APIs: no token passthrough

Real tools call other services, such as the tracker API from lab 3. Forwarding the user's token is forbidden: an MCP server must not pass on the tokens it receives. That token's audience is your server, so a well-built upstream rejects it; worse, forwarding lets one service act with another's credentials and muddles audit logs.

Get a separate credential for each upstream instead: a service credential for the server itself (as TRACKER_API_TOKEN was in lab 3), an OAuth client credentials grant, or, when the upstream must know the user, a token exchange (RFC 8693) or a separate consent flow. Record who called (sub, client_id) in your logs, never the tokens.

07. Under the hood: the same checks without the SDK

The file below implements the same resource-server rules with the standard library only, on port 8091, and adds a scope to every challenge and 405 for GET. It uses HS256, a shared-key signature, with a lab-only key; real servers verify asymmetric signatures against the authorization server's published keys, as remote_server.py does.

Python · remote-lab/rs_stdlib.py (stdlib only)
"""The resource-server checks by hand, stdlib only (LAB: HS256 shared key).

Real deployments verify asymmetric signatures (RS256/ES256) against the
authorization server's JWKS, as remote_server.py does.
"""
import base64
import hashlib
import hmac
import json
import os
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

ISSUER = "http://127.0.0.1:9000/lab"
RESOURCE = "http://127.0.0.1:8091/mcp"
METADATA_PATH = "/.well-known/oauth-protected-resource/mcp"
ALLOWED_ORIGINS = {"http://127.0.0.1:8091", "http://localhost:8091"}
KEY = os.environ.get("LAB_HS256_KEY", "lab-only-key-change-me").encode()
WRITE_TOOLS = {"close_issue"}


def b64(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def unb64(text: str) -> bytes:
    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))


def sign(claims: dict, key: bytes = KEY, alg: str = "HS256") -> str:
    head = b64(json.dumps({"alg": alg, "typ": "JWT"}).encode())
    body = b64(json.dumps(claims).encode())
    mac = hmac.new(key, f"{head}.{body}".encode(), hashlib.sha256).digest()
    return f"{head}.{body}.{b64(mac)}"


def header_value(raw: str | None) -> str | None:
    """Decode the spec's =?base64?...?= form; None if it is malformed."""
    if raw is None or not (raw.startswith("=?base64?") and raw.endswith("?=")):
        return raw
    try:
        return base64.b64decode(raw[9:-2], validate=True).decode("utf-8")
    except ValueError:
        return None


def verify(token: str) -> dict | None:
    """Return the claims if the token is genuine, current and meant for us."""
    try:
        head, body, mac = token.split(".")
        if json.loads(unb64(head)).get("alg") != "HS256":
            return None  # pin the algorithm: never trust the token's choice
        good = hmac.new(KEY, f"{head}.{body}".encode(), hashlib.sha256).digest()
        if not hmac.compare_digest(good, unb64(mac)):
            return None
        claims = json.loads(unb64(body))
    except ValueError:
        return None
    audience = claims.get("aud")
    audiences = audience if isinstance(audience, list) else [audience]
    if (claims.get("iss") != ISSUER or RESOURCE not in audiences
            or not isinstance(claims.get("exp"), int) or claims["exp"] <= time.time()):
        return None
    return claims


class Handler(BaseHTTPRequestHandler):
    def reply(self, status: int, body: object, extra: dict | None = None) -> None:
        data = json.dumps(body).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        for name, value in (extra or {}).items():
            self.send_header(name, value)
        self.end_headers()
        self.wfile.write(data)

    def challenge(self, status: int, error: str, scope: str) -> None:
        value = (f'Bearer error="{error}", scope="{scope}", '
                 f'resource_metadata="http://127.0.0.1:8091{METADATA_PATH}"')
        self.reply(status, {"error": error}, {"WWW-Authenticate": value})

    def do_GET(self) -> None:
        if self.path == METADATA_PATH:  # RFC 9728 Protected Resource Metadata
            self.reply(200, {"resource": RESOURCE, "authorization_servers": [ISSUER],
                             "scopes_supported": ["issues:read", "issues:write"],
                             "bearer_methods_supported": ["header"]})
        elif self.path == "/mcp":
            self.reply(405, {"error": "use POST"}, {"Allow": "POST"})
        else:
            self.reply(404, {"error": "not found"})

    def do_POST(self) -> None:
        origin = self.headers.get("Origin")
        if origin is not None and origin not in ALLOWED_ORIGINS:
            self.reply(403, {"error": "origin not allowed"})  # DNS rebinding
            return
        auth = self.headers.get("Authorization", "")
        claims = verify(auth[7:]) if auth.startswith("Bearer ") else None
        if claims is None:  # missing, forged, expired or for another audience
            self.challenge(401, "invalid_token", "issues:read")
            return
        scopes = claims.get("scope", "").split()
        try:
            msg = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        except (TypeError, ValueError, RecursionError):  # bad, or nested too deep
            self.reply(400, {"jsonrpc": "2.0",
                             "error": {"code": -32700, "message": "Parse error"}})
            return
        params = msg.get("params", {}) if isinstance(msg, dict) else None
        bad_name = isinstance(params, dict) and msg.get("method") == "tools/call" \
            and not isinstance(params.get("name"), str)
        if not isinstance(params, dict) or bad_name:
            self.reply(400, {"jsonrpc": "2.0",  # one request object per POST
                             "error": {"code": -32600, "message": "Invalid Request"}})
            return
        meta = params.get("_meta", {})
        if (self.headers.get("MCP-Protocol-Version")
                != meta.get("io.modelcontextprotocol/protocolVersion")
                or self.headers.get("Mcp-Method") != msg.get("method")
                or (msg.get("method") == "tools/call"
                    and header_value(self.headers.get("Mcp-Name"))
                    != params.get("name"))):
            self.reply(400, {"jsonrpc": "2.0", "id": msg.get("id"),
                             "error": {"code": -32020, "message": "Header mismatch"}})
            return
        needed = {"issues:read"}  # decided from the body, never from headers
        if msg.get("method") == "tools/call" and params.get("name") in WRITE_TOOLS:
            needed.add("issues:write")
        if not needed <= set(scopes):
            self.challenge(403, "insufficient_scope", " ".join(sorted(needed)))
            return
        result = {"resultType": "complete", "content": [
            {"type": "text", "text": f"{msg['method']} ok for {claims['sub']}"}]}
        self.reply(200, {"jsonrpc": "2.0", "id": msg.get("id"), "result": result})

    def log_message(self, *args: object) -> None:
        pass


if __name__ == "__main__":
    print(f"stdlib resource server on {RESOURCE}", flush=True)
    ThreadingHTTPServer(("127.0.0.1", 8091), Handler).serve_forever()

Each test is an attack or a misuse that must fail, from forged, expired and misdirected tokens to Base64-encoded headers, foreign origins and malformed bodies.

Python · remote-lab/test_rs_stdlib.py
"""Negative tests for the resource-server checks: each attack must fail."""
import base64
import json
import threading
import time
import unittest
import urllib.error
import urllib.request

import rs_stdlib as rs

BASE = "http://127.0.0.1:8091"


def token(**changes) -> str:
    claims = {"iss": rs.ISSUER, "aud": rs.RESOURCE, "sub": "user-42",
              "scope": "issues:read", "exp": int(time.time()) + 600}
    return rs.sign(claims | changes)


def post(tok=None, method="tools/list", name=None, headers=None, url="/mcp"):
    params = {"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
                        "io.modelcontextprotocol/clientCapabilities": {}}}
    sent = {"Content-Type": "application/json", "MCP-Protocol-Version": "2026-07-28",
            "Mcp-Method": method}
    if name:
        params |= {"name": name, "arguments": {"number": 101}}
        sent["Mcp-Name"] = name
    if tok:
        sent["Authorization"] = f"Bearer {tok}"
    body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
    req = urllib.request.Request(BASE + url, body.encode(), sent | (headers or {}))
    try:
        resp = urllib.request.urlopen(req, timeout=5)
    except urllib.error.HTTPError as err:
        resp = err
    return resp.status, resp.headers.get("WWW-Authenticate", ""), json.load(resp)


class ResourceServerTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.httpd = rs.ThreadingHTTPServer(("127.0.0.1", 8091), rs.Handler)
        threading.Thread(target=cls.httpd.serve_forever, daemon=True).start()

    @classmethod
    def tearDownClass(cls):
        cls.httpd.shutdown()
        cls.httpd.server_close()

    def test_metadata_names_resource_and_authorization_server(self):
        with urllib.request.urlopen(BASE + rs.METADATA_PATH, timeout=5) as resp:
            doc = json.load(resp)
        self.assertEqual(doc["resource"], rs.RESOURCE)
        self.assertEqual(doc["authorization_servers"], [rs.ISSUER])

    def test_no_token_gets_401_pointing_at_metadata(self):
        status, challenge, _ = post()
        self.assertEqual(status, 401)
        self.assertIn(f'resource_metadata="{BASE}{rs.METADATA_PATH}"', challenge)

    def test_valid_token_is_accepted(self):
        status, _, body = post(token())
        self.assertEqual((status, body["result"]["resultType"]), (200, "complete"))

    def test_rejected_tokens(self):
        head, body, mac = token().split(".")
        forged = rs.b64(json.dumps({"iss": rs.ISSUER, "aud": rs.RESOURCE,
                                    "sub": "user-42", "scope": "issues:write",
                                    "exp": int(time.time()) + 600}).encode())
        cases = {
            "other audience": token(aud="https://api.other.example"),
            "other issuer": token(iss="https://evil.example"),
            "expired": token(exp=int(time.time()) - 5),
            "wrong key": rs.sign({"iss": rs.ISSUER, "aud": rs.RESOURCE,
                                  "exp": int(time.time()) + 600}, key=b"guess"),
            "alg none": rs.b64(b'{"alg":"none","typ":"JWT"}') + f".{body}.",
            "edited claims": f"{head}.{forged}.{mac}",
            "garbage": "not.a.jwt",
        }
        for label, tok in cases.items():
            with self.subTest(label):
                self.assertEqual(post(tok)[0], 401)

    def test_token_in_query_string_is_ignored(self):
        self.assertEqual(post(url=f"/mcp?access_token={token()}")[0], 401)

    def test_write_tool_without_scope_gets_403_with_scopes(self):
        status, challenge, _ = post(token(), "tools/call", "close_issue")
        self.assertEqual(status, 403)
        self.assertIn('error="insufficient_scope"', challenge)
        self.assertIn('scope="issues:read issues:write"', challenge)

    def test_write_tool_with_scope_is_allowed(self):
        tok = token(scope="issues:read issues:write")
        self.assertEqual(post(tok, "tools/call", "close_issue")[0], 200)

    def test_headers_must_match_body(self):
        tok = token(scope="issues:read")
        status, _, body = post(tok, "tools/call", "close_issue",
                               headers={"Mcp-Name": "get_issue"})
        self.assertEqual((status, body["error"]["code"]), (400, -32020))

    def test_base64_tool_name_header_cannot_skip_the_scope_check(self):
        encoded = "=?base64?" + base64.b64encode(b"close_issue").decode() + "?="
        read_only = post(token(), "tools/call", "close_issue",
                         headers={"Mcp-Name": encoded})
        self.assertEqual(read_only[0], 403)
        writer = post(token(scope="issues:read issues:write"), "tools/call",
                      "close_issue", headers={"Mcp-Name": encoded})
        self.assertEqual(writer[0], 200)
        broken = post(token(), "tools/call", "close_issue",
                      headers={"Mcp-Name": "=?base64?not base64!?="})
        self.assertEqual((broken[0], broken[2]["error"]["code"]), (400, -32020))

    def test_malformed_bodies_get_a_clean_400(self):
        bodies = {
            "name is a list": {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
                               "params": {"name": ["close_issue"]}},
            "batch": [{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}],
            "deep nesting": "[" * 100_000 + "]" * 100_000,
            "not JSON": "{oops",
        }
        for label, body in bodies.items():
            raw = body if isinstance(body, str) else json.dumps(body)
            req = urllib.request.Request(
                BASE + "/mcp", raw.encode(),
                {"Content-Type": "application/json", "Mcp-Method": "tools/call",
                 "Authorization": f"Bearer {token()}"})
            with self.subTest(label):
                with self.assertRaises(urllib.error.HTTPError) as ctx:
                    urllib.request.urlopen(req, timeout=5)
                self.assertEqual(ctx.exception.code, 400)
                code = json.load(ctx.exception)["error"]["code"]
                self.assertIn(code, (-32700, -32600))

    def test_foreign_origin_is_refused(self):
        status = post(token(), headers={"Origin": "https://evil.example"})[0]
        self.assertEqual(status, 403)

    def test_get_on_mcp_endpoint_is_405(self):
        req = urllib.request.Request(BASE + "/mcp")
        with self.assertRaises(urllib.error.HTTPError) as ctx:
            urllib.request.urlopen(req, timeout=5)
        self.assertEqual(ctx.exception.code, 405)


if __name__ == "__main__":
    unittest.main()
Terminal
python -m unittest -v test_rs_stdlib
Illustrative output (test ids shortened; the run time differs on every machine)
test_base64_tool_name_header_cannot_skip_the_scope_check ... ok
test_foreign_origin_is_refused ... ok
test_get_on_mcp_endpoint_is_405 ... ok
test_headers_must_match_body ... ok
test_malformed_bodies_get_a_clean_400 ... ok
test_metadata_names_resource_and_authorization_server ... ok
test_no_token_gets_401_pointing_at_metadata ... ok
test_rejected_tokens ... ok
test_token_in_query_string_is_ignored ... ok
test_valid_token_is_accepted ... ok
test_write_tool_with_scope_is_allowed ... ok
test_write_tool_without_scope_gets_403_with_scopes ... ok

----------------------------------------------------------------------
Ran 12 tests in 0.528s

OK

To check that the tests can fail, delete or RESOURCE not in audiences from verify() and run them again: test_rejected_tokens fails on the "other audience" case.

08. Check your understanding

Practice check · 3 questions

Remote servers and OAuth

Answer from the worked example.

Q1. Clients reach your server at `https://mcp.example.com/tracker/mcp`. What should the `resource` field of its metadata document contain?
Q2. A valid token with only `issues:read` calls `close_issue`. Which response lets the client recover by asking for more access?
Q3. Why does `WriteScopeGate` read the tool name from the JSON-RPC body instead of the `Mcp-Name` header?
Practice only: not graded, not saved, not evidence.

09. Apply it

Deploy the skill project's tracker server the same way. Move the tools from lab 3 into a server configured like remote_server.py, with issues:write required for set_issue_state, and give it its own credential for the tracker API. Run it behind HTTPS with your organisation's identity provider in place of the mock (check that it supports the resource parameter and Client ID Metadata Documents), set resource_server_url and the allowed hosts to the public URL, and connect two different MCP hosts to it. Port test_rs_stdlib.py's attacks to run against your deployed server with real tokens.

10. Review prompt

Without looking, draw the seven steps by which a client gets from a 401 to a successful call, naming the RFC behind each document or parameter. Then list everything your server checks on each request, say which failures get 401, 403 or 400, and explain why a server must neither accept tokens issued for another audience nor forward the tokens it receives.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check