Welcome back! In the previous lesson, you learned how to mount your MCP server inside a FastAPI application. This allowed you to serve both your agent tools and regular web API endpoints from a single, scalable app. By combining FastAPI’s flexibility with the power of the MCP server, you are now able to build modern applications that can handle both standard API requests and agent tool calls in one place.
As you continue to build more advanced and production-ready systems, it becomes important to think about security. In real-world scenarios, you do not want just anyone to access your agent tools or sensitive endpoints. Without proper protection, someone could misuse your tools, overload your server, or even access private data. That is why, in this lesson, you will learn how to secure your MCP server using API key authentication. This will help you control who can access your tools and ensure that only trusted agents or users are allowed in.
API key authentication is a simple but effective way to protect your web services. An API key is a secret value — usually a long string — that you give to trusted clients. When a client (like your agent) wants to use your service, it must include this key in its request, usually in a special HTTP header or as a query parameter.
When your server receives a request, it checks for the API key and verifies that it matches the expected value. If the key is missing or incorrect, the server rejects the request. This approach is widely used for internal tools, microservices, and agent integrations because it is easy to implement and works well for server-to-server communication.
By adding API key authentication to your MCP server, you ensure that only clients who know the secret key can access your tools. This is a strong first step toward securing your application.
If you haven’t worked with middleware before, here’s a quick explanation. In web frameworks like FastAPI, middleware is a special layer that sits between the client and your application’s endpoints. Every incoming request passes through the middleware before it reaches your route handlers, and every response passes back through the middleware before it goes to the client.
Middleware is commonly used for tasks that need to happen on every request, such as logging, handling CORS, or — as in this lesson — checking authentication credentials like API keys. By placing your authentication logic in middleware, you ensure that all requests are checked for a valid API key before any sensitive code or data is accessed. This keeps your security logic centralized, consistent, and easy to maintain.
To add API key authentication to your FastAPI app, we will use a middleware to inspect each request for the presence and validity of an API key, and possibly reject requests before they reach your endpoints.
In FastAPI, you can add middleware by creating a class that defines what should happen for each request, and then registering that class with your app. This makes it straightforward to enforce security policies across your entire application.
Here is an example of an authentication middleware you can use:
This middleware checks every incoming request for the correct API key. It looks for the key in the X-API-Key
header. If the key is missing or incorrect, it returns a 401 Unauthorized response with a simple error message. If the key is valid, the request continues as normal, allowing the client to access your regular API endpoints as well as use the MCP tools provided by your server.
For example, if a client sends a request without the correct key, the response will look like this:
This makes it clear to the client that authentication is required.
If you only want to secure your MCP tools and leave your regular API endpoints open, you can easily do this by checking the route where you mounted the MCP server. For example, if you mounted your MCP server at /mcp
, you can have your authentication middleware require an API key only for requests to /mcp
and its subpaths.
Here’s how you can update your middleware to protect just the MCP route:
With this setup, only requests to /mcp
(and anything under it, like /mcp/sse
or /mcp/messages
) will need to include the correct API key. All your other routes, such as /
and /items
, will remain open and won’t require authentication.
This approach is handy when you want to keep your agent tools protected, but still allow easy access to your regular API endpoints. If you ever change the route where you mount your MCP server, just update the MCP_PREFIX
variable in your middleware.
Now that we have our authentication middleware, we need to add it to your FastAPI application. This is done by registering the middleware when creating the FastAPI app. Here is how you can do it:
In this setup, how your ApiKeyMiddleware
works depends on how you configure it:
-
If you protect the whole application: Every request—whether it’s for a regular endpoint like
/
or/items
, or for the MCP server at/mcp
—must include the correct API key. Any request without the right key will be blocked before it reaches your endpoints or tools. -
If you protect only the MCP server route: Only requests to
/mcp
and its subpaths will require the API key. Regular endpoints like/
and/items
will remain open and accessible without authentication. Requests to the MCP server without the correct key will be blocked, but everything else will work as usual.
This gives you flexibility: you can secure your entire application or just your MCP tools, depending on your needs, all within the same FastAPI app.
With your server now protected by API key authentication, your agent must supply the correct key when connecting. This is done by adding the API key to the request headers when the agent connects to the MCP server.
Here is how we can do this in the agent script:
In this example, the agent includes the X-API-Key
header with the value super_secret_value
when connecting to the MCP server. This matches the key expected by your middleware. As a result, the client is able to authenticate and the agent can use the tools provided by your MCP server.
If the client does not supply the correct key, it will receive a 401 Unauthorized error and the agent will not be able to access the tools.
In this lesson, you learned how to secure your MCP server by adding API key authentication using middleware in FastAPI. You saw how the middleware checks each request for the correct API key and blocks unauthorized access. You also learned how to configure your agent to supply the API key when connecting, ensuring a secure communication channel between your agent and the MCP server.
By following these steps, you have taken an important step toward building secure, production-ready applications. You are now ready to practice these skills in hands-on exercises, where you will implement and test API key authentication yourself. Great job integrating security into your advanced MCP server and agent setup!
