How to Secure MCP Servers with OAuth 2.1 in FastAPI

Aug 29, 2025

5

Matt (Co-Founder and CEO)

As AI applications grow in complexity, managing secure, scalable infrastructure for server-to-server communication becomes critical. For those working with MCP (Model Context Protocol) servers, ensuring robust authentication and authorization is essential. This step-by-step guide explores how to implement OAuth 2.1 for MCP servers built on FastAPI, offering technical professionals a transformative strategy to integrate secure and compliant authentication mechanisms.

By the end of this article, you’ll understand how to implement OAuth 2.1 in your FastAPI-based MCP server, why it’s critical for scaling AI applications, and how tools like ScaleKit can simplify the process.

Why OAuth 2.1 is Essential for MCP Server Security


OAuth 2.1

OAuth 2.1 is the industry standard for secure authentication and authorization between clients and servers. It builds on OAuth 2.0, offering a streamlined, safer approach by incorporating best practices such as secure defaults and reduced ambiguities.

For MCP servers - which act as remote interfaces for AI tools - it’s critical to manage not only authentication but also scopes (user-specific permissions). This ensures only authorized clients access your server’s tools and data. Without OAuth 2.1, your infrastructure is vulnerable to unauthorized access, making compliance and trust difficult to maintain.

Overview: What You’ll Build

Imagine an MCP server called Test Tavili, which performs web searches for large language models (LLMs). By the end of this guide:

  • This server will require authentication before granting access.

  • Unauthorized requests will return a 401 Unauthorized error alongside instructions guiding clients toward authentication.

  • Valid tokens will enable authenticated clients to execute tools on the server, such as a web search API.

The solution is built atop FastAPI using ScaleKit, a modular OAuth platform designed for AI applications. You’ll:

  1. Add a discovery endpoint for OAuth metadata.

  2. Implement middleware to manage token validation and unauthorized error handling.

  3. Set up secure scopes to control access to specific server tools.

Step 1: Setting Up Your MCP Server

The starting point is a FastAPI-based MCP server. For context:

  • The server is initialized and mounted at /mcp using the FastMCP library.

  • A simple tool, such as a web search API, is integrated to demonstrate functionality.

Here’s a simplified structure of the server before implementing OAuth:

from fastapi import FastAPI
from fastmcp import MCPServer

app = FastAPI()
mcp_server = MCPServer(name="Tavili")

@app.on_event("startup")
async def startup():
    # Initialize MCP server
    app.mount("/mcp", mcp_server)

At this stage, any client can connect to the server without any authentication. This is where OAuth 2.1 comes into play.

Step 2: Understanding OAuth 2.1 Workflows

OAuth 2.1 introduces a breadcrumb trail system that guides clients through the authentication process. Here’s a high-level summary of the workflow:

  1. The client sends a request to the MCP server.

  2. If the client lacks valid credentials, the server returns a 401 Unauthorized error with a header pointing to a discovery endpoint.

  3. The client follows this endpoint to locate the server’s authentication and token issuance URLs.

  4. The client authenticates with an authorization server (like ScaleKit) to obtain a JSON Web Token (JWT).

  5. On subsequent requests, the client attaches the JWT as a Bearer token in the header.

  6. The server validates the token before granting access.

Step 3: Building the OAuth Discovery Endpoint

The first requirement for OAuth compatibility is a discovery endpoint, which provides metadata about your server’s authentication mechanism. This endpoint is critical for client-server communication.

Here’s how to implement it in FastAPI:

from fastapi import APIRouter
from fastapi.responses import JSONResponse

router = APIRouter()

# OAuth discovery endpoint
@router.get("/.well-known/oauth-protected-resource")
async def oauth_metadata():
    metadata = {
        "issuer": "https://example.com",
        "authorization_endpoint": "https://example.com/oauth/authorize",
        "token_endpoint": "https://example.com/oauth/token",
        "jwks_uri": "https://example.com/.well-known/jwks.json",
        "scopes_supported": ["search:read"],
    }
    return JSONResponse(metadata)

Attach this endpoint to your FastAPI application. Any unauthorized client request to your MCP server will eventually redirect here to learn how to authenticate.

Step 4: Adding Authentication Middleware

The next step is to intercept requests to your MCP server and enforce authentication rules. Middleware is an excellent way to achieve this in FastAPI.

Middleware Flow

  1. Validate if the request includes a Bearer token.

  2. If no token is present, return a 401 Unauthorized error with a header pointing to the discovery endpoint.

  3. Validate the token’s issuer, audience, expiration, and scopes.

Here’s example middleware for token validation using ScaleKit:

from starlette.middleware.base import BaseHTTPMiddleware
from scalekit import ScaleKit, ValidationOptions
from fastapi import HTTPException

class AuthMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, scalekit_client):
        super().__init__(app)
        self.scalekit_client = scalekit_client

    async def dispatch(self, request, call_next):
        # Skip validation for discovery endpoint
        if request.url.path.startswith("/.well-known"):
            return await call_next(request)

        # Extract Bearer token
        auth_header = request.headers.get("authorization")
        if not auth_header or not auth_header.startswith("Bearer "):
            raise HTTPException(status_code=401, detail="Unauthorized")

        token = auth_header.split(" ")[1]

        # Validate token
        options = ValidationOptions(
            issuer="https://example.com",
            audience="https://example.com/mcp"
        )
        try:
            self.scalekit_client.validate_token(token, options)
        except Exception:
            raise HTTPException(status_code=401, detail="Invalid token")

        return await call_next(request)

Attach this middleware to your FastAPI app:

from scalekit import ScaleKit

scalekit_client = ScaleKit(
    client_id="your-client-id",
    client_secret="your-client-secret",
    environment_url="https://example.com"
)
app.add_middleware(AuthMiddleware, scalekit_client=scalekit_client)

Step 5: Testing the Implementation

With the discovery endpoint and middleware in place, you’re ready to test:

  1. Start your MCP server.

  2. Use a compatible MCP client to send a request without credentials. You should receive a 401 Unauthorized response with a discovery URL in the header.

  3. Follow the discovery URL to authenticate and generate a valid JWT.

  4. Repeat the request with the JWT included in the Authorization header. This time, the request should succeed.

Key Takeaways

  • OAuth 2.1 is critical for securing MCP servers and ensuring compliance with modern standards.

  • A discovery endpoint allows clients to retrieve authentication details dynamically.

  • Middleware simplifies request validation, ensuring only authorized clients access resources.

  • Tools like ScaleKit streamline OAuth implementation, handling client registration and token issuance.

  • Properly implemented OAuth 2.1 workflows enhance both security and scalability.

Conclusion

Integrating OAuth 2.1 into your MCP server with FastAPI is essential for building secure, scalable AI applications. By implementing discovery endpoints, authentication middleware, and leveraging tools like ScaleKit, you can simplify the otherwise complex authorization workflows.

This step-by-step guide equips SaaS, AI, and automation professionals to implement robust authentication mechanisms, ensuring your systems are ready for the demands of modern AI applications. Secure your servers today and future-proof your infrastructure for tomorrow.

Source: "Tutorial: Auth for Remote MCP Servers (Step by Step) | OAuth 2.1 with ScaleKit" - Alejandro AO - Software & Ai, YouTube, Aug 25, 2025 - https://www.youtube.com/watch?v=gl6U8s3zStI

Use: Embedded for reference. Brief quotes used for commentary/review.

Related Blog Posts

👉👉👉We're hosting an Agent Infra and MCP Hackathon in Sydney on 14 February 2026 . Sign up here!

👉👉👉

👉👉👉We're hosting an Agent Infra and MCP Hackathon in Sydney on 14 February 2026 . Sign up here!

👉👉👉

👉👉👉We're hosting an Agent Infra and MCP Hackathon in Sydney on 14 February 2026 . Sign up here!

👉👉👉

👉👉👉We're hosting an Agent Infra and MCP Hackathon in Sydney on 14 February 2026 . Sign up here!

👉👉👉