Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 8

Securing Exposed Tools with `AuthConfig` in `FastApiMCP`

Recommended resources

Introduction

Welcome back! In our previous lesson, you crafted and tested a verify_auth dependency, a crucial piece of reusable code for checking a Bearer token. We confirmed it works by temporarily securing our simple root (/) endpoint.

This lesson takes that foundation and applies it to our primary goal: securing the actual tools exposed to the AI model. We will move beyond securing individual endpoints one by one. Instead, you'll learn how to apply your verify_auth dependency globally to all tools managed by the MCP server.

This directly addresses the learning outcome of using the AuthConfig parameter in fastapi_mcp. By the end of this lesson, your entire MCP toolset will be protected, ensuring that only clients with the correct secret token can access it.


1. The Right Way to Secure a Toolset: Dependency Injection

In FastAPI, you could protect each tool by adding Depends(verify_auth) to every single tool's endpoint function (e.g., get_order_details, get_customer_profile). However, this approach has drawbacks:

  • Repetitive: You have to remember to add the dependency to every new tool you create.
  • Error-prone: It's easy to forget, leaving a tool unintentionally exposed.
  • Harder to manage: If you need to change the authentication logic (e.g., add more checks), you'd have to update it in multiple places.

FastAPI's dependency injection system offers a more elegant solution. The fastapi-mcp library leverages this by providing a dedicated configuration object to apply dependencies to an entire set of tools at once.

The image below contrasts the clean, reusable pattern of dependency injection with a less maintainable approach where authentication logic is mixed into the endpoint. We are aiming for the "good" implementation.

FastAPI Authentication with Dependency Injection: Good vs. Bad Practice
This image shows the contrast between a 'good' implementation using FastAPI's dependency injection for authentication and a 'bad' implementation with authentication logic handled directly inside the endpoint. The 'good' approach promotes cleaner, more reusable code.

2. Configuring Global Authentication with AuthConfig

To apply our verify_auth function across all tools, we will use the AuthConfig class provided by fastapi_mcp. This class is the central point for defining the authentication and authorization requirements for an entire MCP instance.

The project guide you're following demonstrates this pattern clearly.

How To Build a MCP Server with FastAPI (FastAPI-MCP)

The guide 'How To Build a MCP Server with FastAPI (FastAPI-MCP)' shows precisely how to use AuthConfig to apply a security dependency to the FastApiMCP instance.

In 'Step 4: Secure and Mount the MCP Server', focus on the snippet where the mcp object is instantiated. Notice the auth_config parameter and how it's used to pass a list of dependencies.

Now, let's modify your main.py file to implement this. You will update the instantiation of your FastApiMCP object.

  1. First, ensure you import AuthConfig from fastapi_mcp and Depends from fastapi.
  2. Then, modify the FastApiMCP constructor call to include the auth_config argument.

Here is the updated code block. Your verify_auth function should already be in the file from the last lesson.




# main.py (updated section)




# ... (your imports and existing code) ...




# Make sure these are imported at the top of your file
from fastapi_mcp import FastApiMCP, AuthConfig
from fastapi import Depends 




# ... (your verify_auth function) ...




# --- MCP Integration ---
mcp = FastApiMCP(
    app,
    name="Apxml API Services",
    description="Tools for managing orders and customers.",
    describe_all_responses=True,
    describe_full_response_schema=True,
    include_operations=[
        "get_order_details",
        "get_customer_profile",
    ],



    # This is the new part:
    auth_config=AuthConfig(
        dependencies=[Depends(verify_auth)],
    ),
)



# Mount the MCP server on a specific path
mcp.mount(mount_path="/mcp")




# This final call scans the app for routes and finalizes the MCP setup.
mcp.setup_server()

With this change, fastapi-mcp will now ensure that the verify_auth dependency is executed and passes successfully before any tool request (get_order_details or get_customer_profile) is processed. You've secured the entire toolset with just a few lines of configuration.


3. Testing the Secured MCP Server

In the previous lesson, we tested our dependency against a regular FastAPI endpoint (/) using the Swagger UI. Now, we must verify that the MCP server itself is properly secured. The best way to do this is with the official MCP Inspector tool, as described in the project guide.

  1. Make sure your FastAPI server is running: uv run uvicorn main:app --reload.
  2. Launch the MCP Inspector you installed previously: npx @modelcontextprotocol/inspector.
  3. Open the Inspector UI in your browser (usually http://localhost:5173).

Test 1: Attempt to Connect Without Authentication

  • Set Transport Type to SSE.
  • Enter the MCP server URL: http://localhost:8000/mcp.
  • Click Connect.

You should see an error. The Inspector will likely report a connection failure or a 401 Unauthorized status. This is excellent! It means our verify_auth dependency is working and rejecting the connection because no token was provided.

Test 2: Connect With Correct Authentication

  • Click the Authentication tab in the Inspector.
  • Under Custom Headers, add a new header:
    • Header Name: Authorization
    • Header Value: Bearer your-super-secret-token (replace with the token from your .env file).
  • Click Connect again.

This time, the connection should be successful. You will see your two tools, get_order_details and get_customer_profile, listed with their descriptions. This confirms that when the correct token is provided, the MCP server grants access.


4. Broader Context: Beyond Static Tokens

We've successfully implemented key-based authentication, which is a great start. It's worth knowing that AuthConfig is designed to handle more advanced authentication schemes as well, most notably OAuth2.

Your experience with bot building might involve connecting to services that use OAuth2 for user-level permissions. MCP supports this flow fully. Instead of just a dependencies list, AuthConfig can be configured with an issuer, authorize_url, and other parameters to manage a full OAuth2 handshake.

The following video discusses the different authentication approaches for MCP, including the more complex but powerful OAuth-based access. You don't need to watch it all, but knowing these concepts exist will be valuable as you build more complex systems.

Python + MCP: Authentication for MCP servers

The video 'Python + MCP: Authentication for MCP servers' provides a high-level overview of different security strategies. It helps place our current key-based approach in the larger context of MCP security.

Watch the segment from 03:58 to 06:26 to understand the three main access strategies: private networks, key-based, and OAuth. Then, you can optionally skim the introduction to OAuth-based access from 20:32 to 21:39 to see the direction more advanced authentication takes.

This shows that the AuthConfig object is your gateway to scaling your server's security model as your application's needs grow.


Conclusion

In this lesson, you've elevated your server's security from a proof-of-concept to a robust, maintainable implementation.

Key Takeaways:

  • The AuthConfig class in fastapi_mcp is the standard mechanism for applying global security rules to an entire MCP toolset.
  • Using AuthConfig with a list of dependencies is a clean, scalable way to enforce authentication, adhering to the DRY (Don't Repeat Yourself) principle.
  • You have successfully secured your MCP server and verified it using the official MCP Inspector, confirming that unauthorized requests are blocked while authorized ones are allowed.

You now have a secure and scalable foundation. In our next lesson, we will dive into your specific goal of creating pre-tool hooks. We'll move beyond authentication and write custom dependencies that perform input validation and apply business logic before a tool is executed, giving you fine-grained control over your AI's actions.