How I Built an MCP Server with OAuth 2.0 in FastAPI

Building an MCP server with OAuth 2.0 in FastAPI comes down to three parts: an MCP server that exposes your tools, an OAuth 2.0 authorization server that signs users in and issues tokens, and a service layer that checks permissions on every single call. Done this way, an AI assistant like Claude can act inside your app with exactly the permissions of the logged-in user, and nothing more. This is how I did it for Cerebro, a CRM where Claude has about 105 tools. You can read the product side in how I built the Cerebro MCP server.

This guide is written against the MCP specification version 2026-07-28 and the official Python SDK 2.3.0. Version 2 of the SDK renamed the server class to MCPServer, so older tutorials that use FastMCP will not match what you see here. All code is simplified for reading and is not production code.

What MCP is and why expose your app through it

The Model Context Protocol (MCP) is an open standard that lets AI applications talk to your software in a uniform way. Your server describes tools, resources and prompts. A client such as Claude discovers them and calls them on behalf of a user.

Think of it as a web API designed for a model instead of a browser. A model does not read your OpenAPI file and guess. It reads tool names and descriptions, picks one, fills in typed arguments and reads the result. That changes how you design the interface, which I come back to later.

Why bother? Because your users already ask assistants to do work. If your CRM, billing tool or internal dashboard has an MCP server, “show me the leads that went quiet this week and draft a follow-up” becomes one request instead of five screens. The risk is also obvious: an assistant with a master key to your data is a security incident waiting to happen. That is why authorization is the heart of this project, not an afterthought.

Architecture: Claude, the MCP server, the authorization server and your service layer

There are four moving parts, and keeping them separate is what makes the design safe.

MCP server with OAuth 2.0 architectureClaude signs the user in at the authorization server and receives a token. It calls the MCP server with that bearer token. The MCP server verifies the token, then calls the FastAPI service layer, which checks permissions again before touching the database.ClaudeMCP clientAuthorization serveryour identity providerMCP serverresource serververifies every tokenFastAPI service layerpermissions checkedagain hereDatabase1. get a token2. call with token3. verify token4. callScopes gate which tools are listed. The service layer checks again.
  1. Authorization server. It signs people in and issues access tokens. You usually do not write this. It is your identity provider, or your own login service.
  2. MCP server. In OAuth terms this is a resource server. It never signs anyone in and never issues tokens. It looks at the Authorization header on each request and decides whether the token is good.
  3. Claude, the MCP client. It discovers which authorization server your MCP server trusts, sends the user through sign-in, gets a token and sends it with every request.
  4. FastAPI service layer. The code that actually reads and writes your data. It receives the identity of the caller and decides again whether this call is allowed.

The MCP authorization specification builds on OAuth 2.1 and a handful of RFCs: protected resource metadata (RFC 9728), resource indicators (RFC 8707) and PKCE. You do not need to implement those from scratch, but you do need to know what you are promising. I link the spec at the end.

Building the MCP server in FastAPI

Install the SDK with uv add "mcp[cli]" or pip install "mcp[cli]". A server is a set of type-hinted Python functions. The type hints become the JSON Schema that the client sees, and the docstring becomes the tool description.

# server.py (simplified example, not production code)
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations

from app.auth import current_user               # defined in the OAuth section below
from app.services import leads as lead_service  # your existing service layer

mcp = MCPServer("Mini CRM")


@mcp.tool(
    title="List leads",
    annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
)
def list_leads(status: str = "new", limit: int = 20) -> list[dict]:
    """List leads the current user is allowed to see, newest first. Filter by status."""
    return lead_service.list_leads(current_user(), status=status, limit=min(limit, 100))


@mcp.tool(
    title="Create lead",
    annotations=ToolAnnotations(destructive_hint=False, idempotent_hint=False),
)
def create_lead(name: str, email: str, company: str = "") -> dict:
    """Create a new lead and return it, including its id."""
    try:
        return lead_service.create_lead(current_user(), name=name, email=email, company=company)
    except lead_service.PermissionDenied as exc:
        raise ToolError(f"You do not have permission to create leads: {exc}") from exc

Two details matter here. First, the annotations are hints for the client, such as “this tool only reads”, and a well-behaved client uses them to decide when to ask the user for confirmation. They are hints, not security, so never rely on a client honouring them. Second, when something goes wrong in a way the model can fix, raise ToolError. The request still succeeds at the protocol level, the result is flagged as an error and the model reads your message and can recover. Never return an error string, because a returned string looks like a successful answer.

Because your MCP server is part of a bigger FastAPI app, mount it instead of running it separately.

# main.py (simplified example, not production code)
from contextlib import asynccontextmanager

from fastapi import FastAPI

from server import mcp

mcp_app = mcp.streamable_http_app()  # call this first: the session manager exists only after it


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with mcp.session_manager.run():
        yield


app = FastAPI(lifespan=lifespan)
# include your normal routers here
app.mount("/", mcp_app)  # keep this last: a mount at "/" matches every path

The lifespan is the line people forget. A mounted sub-application’s own lifespan never runs, so the host app must start the session manager. Without it, the first request to /mcp fails with a “Task group is not initialized” error. Also note that the app only accepts requests addressed to localhost until you pass an allowlist through transport_security=. Behind a real hostname every request is rejected with a 421 until you do. The SDK’s deploy guide covers it.

MCP server OAuth 2.0 FastAPI: the authorization flow

With Streamable HTTP, protecting the server is ordinary OAuth work. The SDK gives you the resource server half: verify tokens, advertise where to get them and refuse everything else. It does not give you a login page or a token issuer.

You provide a TokenVerifier, a class with one async method that takes the raw token and returns an AccessToken or None.

# auth.py (simplified example, not production code)
import jwt
from jwt import PyJWKClient
from pydantic import AnyHttpUrl

from mcp.server.auth.provider import AccessToken, TokenVerifier
from mcp.server.auth.settings import AuthSettings

ISSUER = "https://auth.example.com"
RESOURCE = "https://mcp.example.com/mcp"
jwks = PyJWKClient(f"{ISSUER}/.well-known/jwks.json")  # use your provider's JWKS URL


class JWTVerifier(TokenVerifier):
    async def verify_token(self, token: str) -> AccessToken | None:
        try:
            key = jwks.get_signing_key_from_jwt(token).key
            claims = jwt.decode(token, key, algorithms=["RS256"], audience=RESOURCE, issuer=ISSUER)
        except jwt.PyJWTError:
            return None  # the SDK answers 401 with a WWW-Authenticate header
        return AccessToken(
            token=token,
            client_id=claims.get("azp", claims["sub"]),
            scopes=claims.get("scope", "").split(),
            expires_at=claims.get("exp"),
            resource=RESOURCE,
            subject=claims["sub"],
            claims={"iss": claims["iss"], "roles": claims.get("roles", [])},
        )


auth_settings = AuthSettings(
    issuer_url=AnyHttpUrl(ISSUER),
    resource_server_url=AnyHttpUrl(RESOURCE),
    required_scopes=["crm:read"],
    validate_token_resource=True,
)

# then: MCPServer("Mini CRM", token_verifier=JWTVerifier(), auth=auth_settings)

The token_verifier and auth arguments always travel together. Once they are set, the SDK publishes the protected resource metadata document at /.well-known/oauth-protected-resource/mcp. A client that has never heard of your server calls /mcp with no token, receives a 401 whose WWW-Authenticate header points at that document, reads which authorization server you trust, gets a token there and retries. You wrote none of that discovery logic.

The specification puts several hard requirements on you as the resource server:

  • Tokens must arrive in the Authorization: Bearer header on every request, never in the query string.
  • You must validate that the token was issued for your server as its audience. Clients send a resource parameter during authorization so the token can be bound to your server’s URL. Setting validate_token_resource=True makes the SDK refuse tokens whose resource does not match.
  • Invalid or expired tokens must get a 401. A valid token that lacks the scopes for an operation gets a 403 with an insufficient_scope error.
  • You must not accept or pass through tokens meant for other services.

On the client side, the spec requires clients to use PKCE and to obtain a client ID through one of three mechanisms: client ID metadata documents, pre-registration or dynamic client registration. That is the client’s job, but it explains why your authorization server needs to support at least one of them. Finally, none of this protects the stdio transport. A pipe has no Authorization header, so a local stdio server is secured only by the process that launched it.

Per-user permissions and RBAC

OAuth tells you who is calling. It does not tell you what they may do. Inside any tool, get_access_token() returns the exact AccessToken your verifier built for the current request. I turn that into a small user object once, in one place.

# auth.py, continued (simplified example, not production code)
from dataclasses import dataclass

from mcp.server.auth.middleware.auth_context import get_access_token


@dataclass
class User:
    id: str
    scopes: set[str]
    roles: set[str]


def current_user() -> User:
    token = get_access_token()
    if token is None:
        raise PermissionError("not authenticated")
    return User(
        id=token.subject or token.client_id,
        scopes=set(token.scopes),
        roles=set((token.claims or {}).get("roles", [])),
    )

Then the rule that saved me the most pain: check permissions in the service layer, not in the tool and not in the UI.

# services/leads.py (simplified example, not production code)
class PermissionDenied(Exception):
    pass


def create_lead(user, *, name: str, email: str, company: str = "") -> dict:
    if "crm:write" not in user.scopes or "sales" not in user.roles:
        raise PermissionDenied("the crm:write scope and the sales role are required")
    ...  # validate input, insert the row, write the audit log, return the new lead

The REST API and the MCP server both call this function. They cannot drift apart, because there is only one copy of the rule. A scope in the token says the user granted the assistant that capability. The role says the user is actually allowed to do it. You need both.

What about hiding tools a user cannot use? The high-level MCPServer registers tools statically, so every caller sees the same list. To return a per-user list, drop down to the low-level Server, where you write the tools/list handler yourself and build the ListToolsResult. A permission map keeps that honest.

# simplified example: only advertise tools the caller's scopes allow
from mcp.types import ListToolsResult, Tool

TOOL_SCOPES = {"list_leads": "crm:read", "create_lead": "crm:write"}


def visible_tools(all_tools: list[Tool], scopes: set[str]) -> ListToolsResult:
    return ListToolsResult(tools=[t for t in all_tools if TOOL_SCOPES.get(t.name) in scopes])

Treat the filtered list as a courtesy that reduces noise for the model. The real enforcement is still the check inside the service layer.

Designing 100+ tools the model can use well

With about 105 tools, naming and descriptions matter more than any technical trick. These are the rules I settled on:

  • Use verb_noun names. list_leads, create_lead, update_lead_status. The model should be able to guess the name before it reads the description.
  • One job per tool. A tool that “manages leads” with an action argument forces the model to guess. Separate tools are easier to choose between.
  • Write descriptions for the model. Say what the tool returns, when to use it and when not to. Document every parameter, including allowed values.
  • Group by module. Prefix or organize by area (leads, accounts, documents) so related tools sit together.
  • Separate reads from writes. Mark read tools read-only so clients can run them without friction and slow down for writes.
  • Confirm destructive actions explicitly. Require a confirm argument or use MCP elicitation, so a delete is never a side effect of a vague request.
  • Return consistent, readable errors. Raise ToolError with a sentence that tells the model what to change.

Security checklist

  • Use short-lived access tokens and handle refresh on the client side.
  • Grant least-privilege scopes and ask only for what an operation needs.
  • Enforce permissions on the server, in the service layer, on every call.
  • Validate every argument. The model chooses the inputs, and a model can be manipulated.
  • Rate limit per user and per tool.
  • Write an audit log entry for every tool call: who, which tool, which arguments, the outcome.
  • Never put secrets, tokens or other users’ personal data in tool output.
  • Validate the token audience and reject tokens issued for other services.

Lessons from Cerebro

Building this for a real CRM taught me four things I would repeat.

  1. Put permissions in the service layer, not the UI. Then the REST API and the MCP server enforce the same rules by construction.
  2. Keep tools narrow and well described. Clear names and descriptions matter more to the model than how many tools you ship.
  3. Separate read tools from write tools, and require explicit confirmation for destructive actions.
  4. Self-host the channels you can. In Cerebro, self-hosting the WhatsApp gateway gave full control over message data and costs.

Frequently asked questions

What is an MCP server?

An MCP server is a program that exposes tools, resources and prompts to AI applications through the Model Context Protocol. A client such as Claude connects to it, lists what is available and calls tools with typed arguments on behalf of a user.

Does an MCP server need OAuth?

Not for local use. A stdio server runs as a local process and is secured by whoever launches it. Over HTTP, where your server is a normal web service reachable by others, you should protect it, and the MCP authorization specification is built on OAuth 2.1 for exactly that reason.

Can I add MCP to an existing FastAPI app?

Yes. Build the MCP server with the SDK, get its ASGI app from streamable_http_app(), mount it after your own routes and start its session manager from your app’s lifespan. Your existing service layer then backs both the REST API and the MCP tools.

Conclusion

The pattern is simple to state and takes discipline to keep: your MCP server only verifies tokens, your authorization server issues them and your service layer decides what each user may do. If you want to see it running in a real product, read the Cerebro case study. If you want the same thing for your own API, you can hire me to build an MCP server for your product.

References: the MCP authorization specification and the MCP Python SDK authorization guide.