FastAPI MCP: Turning Your Endpoints into AI-Ready Tools
In a nutshell, fastapi_mcp is a Python library that helps you easily expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with built-in authentication.
So, what does that actually mean?
FastAPI endpoints
These are the functions in your FastAPI application that handle web requests. They define the logic for your APIs.
Model Context Protocol (MCP)
This is a specification that allows AI models (like large language models) to understand and use external tools. Think of it as a standardized way for an AI to know what an API does, what parameters it needs, and what kind of response it returns. This enables the AI to call your API to perform actions in the real world (e.g., retrieving data, sending an email, etc.).
Authentication
fastapi_mcp includes a simple, pre-built authentication mechanism to ensure that only authorized clients (like your AI model) can access these tools.
Essentially, fastapi_mcp bridges the gap between your existing FastAPI services and powerful AI models, allowing the AI to interact with your services intelligently and securely.
This library is incredibly useful because it lets you
Transform your APIs into AI-ready tools with minimal effort. You don't need to manually create complex tool schemas or write custom integration logic. fastapi_mcp automates this process for you.
Focus on your business logic. You can continue building your FastAPI application as you normally would. The library handles the AI-specific integration details in the background.
Enhance security. The built-in authentication ensures that your endpoints are not exposed to the public internet without proper authorization. This is a critical feature for any production environment.
Promote reusability. Once you've created a tool with fastapi_mcp, it can be used by any AI model that supports the MCP standard. This makes your services more versatile and future-proof.
Getting started is super straightforward. First, you need to install the library.
pip install fastapi_mcp
Next, you'll need to set up a simple FastAPI application. Here’s a basic example.
# main.py
from fastapi import FastAPI, Depends
from fastapi_mcp import FastAPIMCP, get_auth_token
app = FastAPI()
mcp_app = FastAPIMCP(app=app, title="My Awesome Tools")
# This is an example of a dependency that checks for the auth token
# In a real-world scenario, you might want a more robust authentication system
def get_current_user(token: str = Depends(get_auth_token)):
if token != "my-secret-token":
raise HTTPException(status_code=401, detail="Invalid token")
return {"user": "authorized_user"}
# This is the endpoint we want to expose as an AI tool
@mcp_app.tool
@app.get("/weather")
def get_current_weather(city: str, current_user: dict = Depends(get_current_user)):
"""
Get the current weather for a given city.
Args:
city: The name of the city to get the weather for.
Returns:
A dictionary with the city and its current temperature.
"""
# In a real application, you'd call a weather API here
return {"city": city, "temperature": 25, "unit": "celsius"}
# You can add regular FastAPI endpoints that are not exposed as tools
@app.get("/")
def read_root():
return {"Hello": "World"}
In this example, we
Create an instance of FastAPIMCP and pass our FastAPI app to it.
Define a simple dependency (get_current_user) to handle authentication. fastapi_mcp provides a get_auth_token dependency to help with this.
Use the @mcp_app.tool decorator on our /weather endpoint. This is the magic step! It tells fastapi_mcp to expose this endpoint as an AI tool.
The docstring of the function is used to create the description of the tool, which is super important for the AI to understand its purpose.
To run this application, you'd use uvicorn
uvicorn main:app --reload
Once your application is running, you can access the MCP-formatted tool specification. fastapi_mcp automatically generates this for you.
You can view the specification at a special endpoint, which is /mcp by default. If you make a GET request to http://127.0.0.1:8000/mcp, you'll get a JSON response that describes your tools.
Here’s a simplified version of what that JSON might look like
{
"title": "My Awesome Tools",
"description": "API endpoints exposed as MCP tools.",
"openapi": "3.1.0",
"servers": [
{
"url": "http://localhost:8000"
}
],
"components": {
"securitySchemes": {
"bearerAuth": {
"type": "http",
"scheme": "bearer"
}
}
},
"paths": {
"/weather": {
"get": {
"operationId": "get_current_weather",
"description": "Get the current weather for a given city.",
"parameters": [
{
"name": "city",
"in": "query",
"required": true,
"schema": {
"title": "City",
"type": "string"
}
}
],
"security": [
{
"bearerAuth": []
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
}
}
}
This JSON is what your AI model will consume to understand how to use your /weather tool. The fastapi_mcp library handles all this generation for you, saving you from a lot of manual work.