Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Secure a remote MCP server with OAuth

Protect a Streamable HTTP MCP server with OAuth 2.1 as the 2026-07-28 spec requires: resource metadata, audience checks, per-tool scopes and Inspector tests.

By Advanced1 h 15 min hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

A local MCP server runs as you, so it can use your credentials. A remote server is different: anyone who can reach the URL can call its tools unless you stop them. The MCP specification’s answer is OAuth 2.1, with the MCP server acting as a resource server that checks access tokens and an identity provider (the authorisation server) that issues them.

This tutorial secures the notes server from Build an MCP server in Python in three stages: local development tokens, per-tool scopes, and a production setup against a real identity provider. It follows the authorisation section of the 2026-07-28 MCP specification and FastMCP 4.2, both checked on 20 November 2026.

What the spec asks of a server

You do not need to read the whole authorisation chapter to build a compliant server, but you do need these rules. Quotes are from the 2026-07-28 revision.

  • Advertise your authorisation server. “MCP servers MUST implement OAuth 2.0 Protected Resource Metadata (RFC9728).” This is a small JSON document listing which authorisation servers issue tokens for you and which scopes you support.
  • Point clients at it. A request without a valid token gets 401 Unauthorized with a WWW-Authenticate: Bearer header containing resource_metadata="..." and, ideally, the scope the request needs.
  • Check the audience. “MCP servers MUST validate that access tokens were issued specifically for them as the intended audience.” A token minted for some other API must be rejected even if it is otherwise valid.
  • Never pass tokens through. “MCP servers MUST NOT accept or transit any other tokens.” If your tools call a downstream API, get a separate token for that API. Forwarding the client’s token is the confused-deputy pattern the spec forbids.
  • Use the right status codes. 401 for a missing, invalid or expired token; 403 with error="insufficient_scope" when the token is valid but lacks a scope.
  • Tokens only in the header. Authorization: Bearer ... on every request, never in the query string.

Clients have their own duties: PKCE, sending the resource parameter (RFC 8707) so tokens are bound to your server, and validating the iss parameter. Client registration now prefers Client ID Metadata Documents; Dynamic Client Registration is deprecated in this revision but still allowed. Most of that is your identity provider’s and the host’s job, not yours.

1. Local development with static tokens

Start with fake tokens so you can test the server’s behaviour without an identity provider. FastMCP’s StaticTokenVerifier maps fixed token strings to identities and scopes. It stores tokens in plain text, so it is for development only.

# server.py
import os
from pathlib import Path

from fastmcp import FastMCP
from fastmcp.server.auth import require_scopes
from fastmcp.server.auth.providers.jwt import StaticTokenVerifier
from fastmcp.server.dependencies import get_access_token

NOTES_DIR = Path(os.environ.get("NOTES_DIR", "./notes")).resolve()

verifier = StaticTokenVerifier(
    tokens={
        "dev-reader": {"client_id": "alice@example.com", "scopes": ["notes:read"]},
        "dev-writer": {"client_id": "bob@example.com", "scopes": ["notes:read", "notes:write"]},
    },
    required_scopes=["notes:read"],
)

mcp = FastMCP("notes", auth=verifier)


def safe_path(name: str) -> Path:
    path = (NOTES_DIR / name).resolve()
    if not path.is_relative_to(NOTES_DIR):
        raise ValueError("Path is outside the notes folder")
    return path


@mcp.tool
def search_notes(query: str) -> list[str]:
    """Return the names of Markdown notes whose text contains the query (case-insensitive)."""
    q = query.lower()
    return sorted(
        p.name for p in NOTES_DIR.glob("*.md") if q in p.read_text(encoding="utf-8").lower()
    )


@mcp.tool
def read_note(name: str) -> str:
    """Return the full text of one note, by file name (for example 'rollback.md')."""
    return safe_path(name).read_text(encoding="utf-8")


@mcp.tool(auth=require_scopes("notes:write"))
def append_to_note(name: str, text: str) -> str:
    """Append a line of text to an existing note. Requires the notes:write scope."""
    token = get_access_token()
    who = token.client_id if token else "unknown"
    path = safe_path(name)
    if not path.exists():
        raise ValueError(f"No note called {name}")
    with path.open("a", encoding="utf-8") as f:
        f.write(f"\n{text}  (added by {who})\n")
    return f"Appended to {name}"

What each piece does:

  • required_scopes=["notes:read"] means every request needs at least notes:read. A token without it is rejected before any tool runs.
  • @mcp.tool(auth=require_scopes("notes:write")) adds a second check on the one tool that changes data. Clients without the scope do not see the tool at all, and a direct call to it fails.
  • get_access_token() gives the tool the verified identity, so the write is attributed to a real client rather than “the server”.

Run it over HTTP:

mkdir -p notes && printf "# Rollback\nRun ./deploy --rollback\n" > notes/rollback.md
uv run fastmcp run server.py --transport http --port 8000

2. Prove the rules hold, with curl

Test the HTTP layer directly before you involve a model. A request without a token:

curl -i -X POST http://localhost:8000/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'

You should get HTTP/1.1 401 Unauthorized and a WWW-Authenticate: Bearer ... header. Now repeat with -H "Authorization: Bearer dev-reader". The 401 goes away. Depending on how your FastMCP version negotiates protocol versions, the body may be a tool list or a protocol error asking for the 2026-07-28 request metadata; either way you are past authentication, which is what this check is for. Full protocol calls are easier in Inspector.

3. Test scopes in MCP Inspector

Start Inspector:

npx @modelcontextprotocol/inspector

In the browser UI, choose the Streamable HTTP transport, enter http://localhost:8000/mcp, and add an Authorization header with the value Bearer dev-reader. Connect, then:

  1. List tools. Only search_notes and read_note appear. FastMCP hides tools whose scope check the token fails, so a read-only client never even sees the write tool.
  2. Call search_notes with rollback. It returns ["rollback.md"].
  3. Reconnect with Bearer dev-writer and list tools again. Now append_to_note appears too.
  4. Call append_to_note with rollback.md and some text. It succeeds, and the note records bob@example.com.
  5. Reconnect with Bearer wrong-token. The connection fails with 401.

Write these down as your acceptance tests. Every change to auth code should be re-run against them, ideally as automated tests with FastMCP’s client.

4. Production: verify real JWTs

Static tokens prove the logic. In production, tokens come from your identity provider and the server verifies them with the provider’s public keys. Replace the verifier:

# auth.py
import os

from fastmcp.server.auth import RemoteAuthProvider
from fastmcp.server.auth.providers.jwt import JWTVerifier
from pydantic import AnyHttpUrl

ISSUER = os.environ["OAUTH_ISSUER"]                # e.g. https://auth.example.com/
JWKS_URI = os.environ["OAUTH_JWKS_URI"]            # e.g. https://auth.example.com/.well-known/jwks.json
PUBLIC_URL = os.environ["MCP_PUBLIC_BASE_URL"]     # e.g. https://notes.example.com (no /mcp)

verifier = JWTVerifier(
    jwks_uri=JWKS_URI,
    issuer=ISSUER,
    audience=f"{PUBLIC_URL}/mcp",                 # the canonical URI of this server
    required_scopes=["notes:read"],
)

auth = RemoteAuthProvider(
    token_verifier=verifier,
    authorization_servers=[AnyHttpUrl(ISSUER)],
    base_url=PUBLIC_URL,
)

Then in server.py, drop the StaticTokenVerifier and use mcp = FastMCP("notes", auth=auth) with from auth import auth.

JWTVerifier checks the signature against the provider’s published keys, the issuer, the expiry and the audience. The audience check is the one that matters most for MCP: configure your identity provider so tokens requested for this server carry its canonical URL (https://notes.example.com/mcp) as the audience. Clients send that URL as the resource parameter when they ask for a token. Providers differ in how they map resource to aud; check yours issues tokens with the exact value you configure here.

RemoteAuthProvider serves the Protected Resource Metadata document and adds resource_metadata to 401 responses, so clients can discover your identity provider without any configuration.

Check the discovery chain from the outside once it is deployed:

curl -si -X POST https://notes.example.com/mcp \
  -H "Accept: application/json, text/event-stream" \
  -H "Content-Type: application/json" -d '{}' | grep -i www-authenticate

# then fetch the URL from resource_metadata="..."
curl -s https://notes.example.com/.well-known/oauth-protected-resource | jq

The metadata should name your issuer under authorization_servers and list notes:read and notes:write under scopes_supported. If the header points at a path with /mcp appended, fetch that one; the header is the source of truth.

Finally connect a real host. In Claude Code:

claude mcp add --transport http notes https://notes.example.com/mcp

Run /mcp, choose the server, and complete the browser sign-in. If your provider does not support Client ID Metadata Documents or dynamic registration, register a client manually and pass it: claude mcp add --transport http --client-id YOUR_ID --client-secret --callback-port 8080 notes https://notes.example.com/mcp.

Scope design

Scopes are the part of this you will live with longest. Some rules that hold up:

  • Split read from write. Most agent use is reading. Give hosts read scopes by default and make write a deliberate grant.
  • Advertise the minimum. The spec treats scopes_supported as the minimal set for basic use, with more requested by step-up when a tool needs them. When a call needs a scope the token lacks, return 403 with error="insufficient_scope" and the required scope, and the client can ask the user for more.
  • Name scopes for actions, not tools. notes:write survives a refactor; append_to_note does not.
  • Do not put offline_access in your challenges. Refresh tokens are between the client and the identity provider.

Pitfalls

Accepting any valid JWT from your issuer. Without an audience check, a token for your billing API works on your MCP server. Always set audience.

Forwarding the user’s token to another API. It is explicitly forbidden. Use a token exchange or a service credential scoped to what the tool needs.

Running without TLS. Bearer tokens over plain HTTP can be read in transit. Terminate TLS in front of the server.

Binding to 0.0.0.0 in development. The transport spec says local servers should bind to 127.0.0.1 and must validate the Origin header, to stop DNS rebinding from a web page.

Trusting the tool output. Auth controls who can call your tools, not what the text they return does to the model. Notes written by other people can contain prompt injection. See MCP security.

Next steps

Covers

Check your understanding

Remote MCP server security quiz

OAuth roles for a remote MCP server, Protected Resource Metadata, 401 and 403 responses, audience checks, token passthrough, per-tool scopes and production pitfalls.

9 questions · pass mark 70%

Question 1 of 90 answered
  1. In the MCP specification's authorisation model, what role does your remote MCP server play?
Back to top