Introduction
Welcome back! In the last lesson, you successfully defined your first tool—an API endpoint named get_order_details—complete with a Pydantic response model and a descriptive operation_id. You now have a standard FastAPI endpoint ready to be exposed.
This lesson is the pivotal step where we bridge the gap between your API and the AI. Our goal is to integrate fastapi-mcp into the FastAPI app to expose your single endpoint as a tool.
We'll add a few lines of code that instruct the fastapi-mcp library to scan your application, find the endpoint you created, and make it discoverable through a special Model Context Protocol (MCP) endpoint. Your experience with Rasa will be useful here; think of this integration as creating the standardized communication channel, much like how Rasa's core server exposes endpoints for channel connectors to use.
Let's begin.
1. The fastapi-mcp Integration Layer
At its core, fastapi-mcp is a library that acts as an intelligent integration layer. It introspects your FastAPI application—looking at its routes, path parameters, Pydantic models, and operation_ids—and automatically generates the necessary MCP server logic.
This means you don't have to write custom code to handle the MCP protocol. You define standard FastAPI endpoints, and fastapi-mcp handles the rest.
The following diagram provides a great visual model for what we are about to build. We are adding the "FastAPI-MCP Integration Layer" to our existing application.

2. Adding MCP to Your Application
Integrating fastapi-mcp is a straightforward process that involves three key steps: importing the class, instantiating it with your FastAPI app object, and then mounting it.
To start, let's get a clear, step-by-step guide on this process.
Bridge the Gap: Exposing FastAPI Endpoints as AI Tools with MCP
The article 'Bridge the Gap' provides a concise, well-explained code example for integrating fastapi-mcp. We will follow its structure.
Please read the section 'The FastAPI Server (main.py)'. Pay close attention to the Breakdown which explains the purpose of each step: app = FastAPI(...), @app.get(...), mcp = FastApiMCP(app), and mcp.mount(). This directly corresponds to what we will now implement.
Now, let's apply this to your main.py file. Open the file and add the following code at the very end, after all your @app.get(...) routes have been defined.
- Import
FastApiMCP: First, you need to import the class from the library. - Instantiate
FastApiMCP: Create an instance ofFastApiMCP. You must pass your existingappobject to its constructor. This is how the library gains access to your application's structure. - Mount the MCP server: Call the
.mount()method. This adds the required/mcpendpoint to your application. - Finalize the setup: Call the
.setup_server()method. This is a best practice recommended in the guide you're following. It scans all the registered routes and finalizes the MCP configuration, ensuring everything is correctly wired up.
Add the following highlighted lines to the bottom of your main.py:
# ... (your existing imports, app definition, Order model, and endpoints)
@app.get(
"/orders/{order_id}",
operation_id="get_order_details",
description="Fetches detailed information for a specific order by its ID.",
response_model=Order,
)
async def get_order_details(order_id: str) -> dict:
# ... (your existing function logic)
if order_id == "ORD12345":
return {
"order_id": order_id,
"customer_id": 101,
"status": "shipped",
"total_amount": 199.99,
"currency": "USD",
}
raise HTTPException(status_code=404, detail="Order not found")
# --- Add the following lines ---
from fastapi_mcp import FastApiMCP
# 1. Instantiate the MCP server, passing it your FastAPI app instance.
mcp = FastApiMCP(
app,
name="My Awesome MCP Server",
description="Tools for managing orders and customers.",
)
# 2. Mount the MCP server on the default '/mcp' path.
mcp.mount()
# 3. Finalize the server setup after all routes are defined.
mcp.setup_server()
Why at the end?
Placing this integration code after your route definitions is crucial. FastApiMCP(app) inspects the app object at the moment it is called. To ensure it discovers all your endpoints, you must define them first.
For a visual walkthrough of this process, the following video demonstrates the same core steps of importing and wrapping the FastAPI app.
Create MCP Servers from Python Code in 10.5 Minutes
The video 'Create MCP Servers from Python Code' visually demonstrates the integration. While it uses slightly different code, the core concept of wrapping the app object is identical.
Watch from 02:13 to 03:15. This section shows the process of importing FastApiMCP and adding the lines to instantiate and apply it to the FastAPI application file, reinforcing the code you just added.
3. What Have You Built?
With just a few lines of code, you have fundamentally enhanced your FastAPI application. Your server, which is likely still running with --reload, has now automatically:
- Scanned your application for API routes.
- Identified the
get_order_detailsendpoint as a potential tool. - Created a new endpoint at
http://127.0.0.1:8000/mcp.
This /mcp endpoint is not a typical REST API endpoint that returns JSON. It uses a protocol called Server-Sent Events (SSE) to communicate with AI clients. If you were to visit it in your browser now, you wouldn't see a clean JSON object, but rather a stream of event and data messages. This is the expected behavior and confirms that your MCP server is active.
Conclusion
Excellent work. You have successfully integrated fastapi-mcp and transformed your simple API endpoint into a discoverable AI tool.
The key takeaways from this lesson are:
fastapi-mcpacts as an integration layer that automatically exposes FastAPI endpoints.- The integration process involves instantiating
FastApiMCPwith your app, mounting it with.mount(), and finalizing with.setup_server(). - This code must be placed after your API route definitions to ensure they are discovered.
- The result is a new
/mcpendpoint that speaks the language of AI clients.
In our next lesson, we will complete this module by learning how to verify that your tool is correctly exposed. We'll do this by inspecting the output of the /mcp endpoint and seeing how the information from your Pydantic model and operation_id is presented to the AI.