Secure a remote MCP server with OAuth access tokens

Day 3, 30 minutes · advanced

Goal of this lessonExplain the OAuth roles and discovery steps in MCP, then protect a copy of Romy's server so it only answers requests with a valid access token.

Why it matters

Right now anyone who can reach Romy's HTTP server can use every tool on it. On localhost that is only you. The moment a server is on the internet, it needs to know who is calling and what they may do. Otherwise a stranger can fill Romy's wish list or read data that is not theirs.

MCP solves this with OAuth, the same standard many websites use for "sign in with" buttons. In this lesson you learn the parts of the MCP authorization flow: who plays which role, how a client finds out where to get a token, how tokens travel, and why a server must never pass a token on. Then you build a protected copy of Romy's server and watch it turn away requests without a valid token. At the end you have quillfeather_secure.py and you have seen its 401 and its refusals yourself.

The words you need today

  • OAuth 2.1: the authorization standard MCP builds on. It lets a user give an app limited access without sharing a password.
  • Access token: a string that proves a client may make a request. It is sent as a bearer token: whoever holds it can use it.
  • Scope: a named permission inside a token, such as shop:read.
  • Audience: the server a token was issued for. A token for another server must be refused.
  • PKCE: an extra check in the sign-in flow, so a stolen authorization code is useless.

Three roles

The authorization page of the specification names three parties:

Role Who What it does
Resource server Romy's MCP server Checks the token on every request. Never issues tokens.
Client Claude Code, the Inspector, your app Gets a token for the user and sends it along.
Authorization server An identity product (the spec does not prescribe one) Signs the user in and issues tokens.

Authorization is optional, and it is meant for HTTP transports. A stdio server should get its credentials from the environment instead.

The flow, step by step

From the specification and the MCP authorization tutorial:

  1. The client sends a request without a token. The server answers 401 Unauthorized with a WWW-Authenticate header. Its resource_metadata points to a metadata document.
  2. The client fetches that Protected Resource Metadata document. It lists authorization_servers and scopes_supported. For an endpoint at /mcp it lives at /.well-known/oauth-protected-resource/mcp.
  3. The client fetches the authorization server's own metadata and checks that its issuer matches.
  4. The client identifies itself. A client with pre-registered details uses those first. When client and server have never met, the spec recommends a Client ID Metadata Document: an HTTPS address of a small JSON file about the client. Dynamic Client Registration is deprecated as of 2026-07-28.
  5. The browser opens for the user to sign in. The request carries a PKCE challenge, the scopes and a resource parameter with the server's address, so the token is bound to that server.
  6. The client sends Authorization: Bearer <token> on every HTTP request, never in the address.

Rules a server must keep

  • Check the audience. The specification says servers must check that a token was issued for them, and must not accept or pass on any other token.
  • No token passthrough. If Romy's server called a payment service, it would need its own token for that service. Forwarding the client's token is explicitly forbidden.
  • Keep scopes small. List only what basic use needs in scopes_supported and ask for more later. A valid token that lacks a scope gets 403 Forbidden with insufficient_scope. In a test with a token without shop:read, the Python SDK answered exactly that.

What the Python SDK does for you

The SDK's authorization page says your server is the resource server only. You write a TokenVerifier with one method, verify_token, that returns an AccessToken or None. AuthSettings names the issuer, your own address and the required scopes. The SDK then adds the metadata route, answers without a valid token with a 401 and makes get_access_token() available in your tools. It does not give you a login page or tokens. In this exercise a small table of practice tokens plays the authorization server. A real verifier checks a signed token or asks the authorization server. If you add the protected server to Claude Code without a token, it follows the metadata pointer and tries to reach auth.example.com, which does not exist, so claude mcp list shows Failed to connect.

Hugo's practice token has only shop:read. Romy's has shop:read and wishlist:write. The server needs shop:read for every request, and the wish list tool also checks for wishlist:write.

The steps

  1. Copy the HTTP server to quillfeather_secure.py.
  2. Add the token verifier and settings in place of the server line.
  3. Add a scope check to the wish list tool.
  4. Start the protected server.
  5. Send a request without a token and read the 401 and the metadata.
  6. Try the Inspector without a token, then with Hugo's and Romy's tokens.

Follow the steps below.

Today's actions

Ticks are not saved without an account

Do it in Claude API

Claude API

  1. Stop the lesson 1 server with Ctrl+C. Then copy it to a new file for the protected version.
    cp quillfeather_remote.py quillfeather_secure.py
  2. In quillfeather_secure.py, replace everything from from mcp.server import MCPServer down to mcp = MCPServer("quillfeather") with this block. Leave the import lines above it as they are.
    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
    
    logger = logging.getLogger(__name__)
    
    RESOURCE = "http://localhost:8000/mcp"
    
    # Practice tokens for this exercise only. A real server never keeps tokens in
    # its code: it checks tokens that an authorization server issued for it.
    PRACTICE_TOKENS = {
        "practice-token-romy": AccessToken(
            token="practice-token-romy", client_id="romy-laptop",
            scopes=["shop:read", "wishlist:write"], resource=RESOURCE,
        ),
        "practice-token-hugo": AccessToken(
            token="practice-token-hugo", client_id="hugo-phone",
            scopes=["shop:read"], resource=RESOURCE,
        ),
    }
    
    
    class PracticeTokenVerifier(TokenVerifier):
        async def verify_token(self, token: str) -> AccessToken | None:
            return PRACTICE_TOKENS.get(token)
    
    
    mcp = MCPServer(
        "quillfeather-secure",
        token_verifier=PracticeTokenVerifier(),
        auth=AuthSettings(
            issuer_url=AnyHttpUrl("https://auth.example.com"),
            resource_server_url=AnyHttpUrl(RESOURCE),
            required_scopes=["shop:read"],
            validate_token_resource=True,
        ),
    )
  3. In the function add_to_wishlist, paste these lines directly under its docstring, above book = BOOKS.get(...). They refuse tokens without the wishlist:write scope.
        token = get_access_token()
        if token is None or "wishlist:write" not in token.scopes:
            raise ToolError("This token may not change the wish list. It needs the wishlist:write scope.")
  4. Start the protected server and leave this terminal open.
    uv run quillfeather_secure.py
  5. In a second terminal, send a request without a token, then fetch the metadata document. You should see 401 Unauthorized with a WWW-Authenticate header, then JSON with authorization_servers. In Windows PowerShell type curl.exe instead of curl.
    curl -i -X POST http://localhost:8000/mcp
    curl http://localhost:8000/.well-known/oauth-protected-resource/mcp
  6. Try the Inspector without a token. --stored-auth-only stops it from starting a sign-in. You should see auth_required. Check the exit code: $LASTEXITCODE in PowerShell or echo $? on macOS and Linux shows 3.
    npx @modelcontextprotocol/inspector --cli http://localhost:8000/mcp --transport http --stored-auth-only --method tools/list
  7. Now send Hugo's practice token. The stock check works, but adding to the wish list is refused with your scope message.
    npx @modelcontextprotocol/inspector --cli http://localhost:8000/mcp --transport http --header "Authorization: Bearer practice-token-hugo" --method tools/call --tool-name check_stock --tool-arg "title=Moby Dick"
    npx @modelcontextprotocol/inspector --cli http://localhost:8000/mcp --transport http --header "Authorization: Bearer practice-token-hugo" --method tools/call --tool-name add_to_wishlist --tool-arg "title=Little Women" --tool-arg customer=Hugo
  8. Send the same wish list call with Romy's token, which has both scopes. It is added. Write in mcp-notes.txt which calls were refused and why. Stop the server with Ctrl+C.
    npx @modelcontextprotocol/inspector --cli http://localhost:8000/mcp --transport http --header "Authorization: Bearer practice-token-romy" --method tools/call --tool-name add_to_wishlist --tool-arg "title=Little Women" --tool-arg customer=Hugo

Note: The practice tokens are plain words on purpose and only work on your own computer. Never put real tokens in code or in a command you share. auth.example.com is a placeholder: there is no real sign-in behind it.

Checked on 4 December 2026 · Source: MCP Python SDK: Authorization (opens in a new tab)

Create a free account to save your progress. Sign in or sign up