FastAPI-MCP is simply a zero-configuration instrumentality that seamlessly exposes FastAPI endpoints arsenic Model Context Protocol (MCP) tools. It allows you to equine an MCP server straight wrong your FastAPI app, making integration effortless.
In this tutorial, we’ll research really to usage FastAPI-MCP by converting a FastAPI endpoint—which fetches alerts for U.S. nationalist parks utilizing nan National Park Service API—into an MCP-compatible server. We’ll beryllium moving successful Cursor IDE to locomotion done this setup measurement by step.
National Park Service API
To usage nan National Park Service API, you tin petition an API cardinal by visiting this link and filling retired a short form. Once submitted, nan API cardinal will beryllium sent to your email.
Make judge to support this cardinal accessible—we’ll beryllium utilizing it shortly.
Cursor IDE Installation
You tin download nan Cursor IDE from cursor.com. It is built specifically for AI-assisted development. It’s free to download and comes pinch a 14-day free trial.
Python Dependencies
Run nan pursuing bid to download nan required libraries:
pip instal fastapi uvicorn httpx python-dotenv pydantic fastapi-mcp mcp-proxy
We will beryllium creating a elemental FastAPI app that uses nan National Park Service API to springiness alerts related to US National Parks. Later we will person this app into an MCP server.
First create a .env record and shop your API key
NPS_API_KEY=<YOUR_API_KEY>
Replace <YOUR_API_KEY> pinch nan 1 you generated.Now, create a caller record named app.py and paste nan pursuing code. This will service arsenic nan halfway logic of your application:
from fastapi import FastAPI, HTTPException, Query
from typing import List, Optional
import httpx
import os
from dotenv import load_dotenv
from fastapi_mcp import FastApiMCP
# Load situation variables from .env file
load_dotenv()
app = FastAPI(title="National Park Alerts API")
# Get API cardinal from situation variable
NPS_API_KEY = os.getenv("NPS_API_KEY")
if not NPS_API_KEY:
raise ValueError("NPS_API_KEY situation adaptable is not set")
@app.get("/alerts")
async def get_alerts(
parkCode: Optional[str] = Query(None, description="Park codification (e.g., 'yell' for Yellowstone)"),
stateCode: Optional[str] = Query(None, description="State codification (e.g., 'wy' for Wyoming)"),
q: Optional[str] = Query(None, description="Search term")
):
"""
Retrieve parkland alerts from nan National Park Service API
"""
url = "https://developer.nps.gov/api/v1/alerts"
params = {
"api_key": NPS_API_KEY
}
# Add optional parameters if provided
if parkCode:
params["parkCode"] = parkCode
if stateCode:
params["stateCode"] = stateCode
if q:
params["q"] = q
try:
async pinch httpx.AsyncClient() arsenic client:
consequence = await client.get(url, params=params)
response.raise_for_status()
return response.json()
isolated from httpx.HTTPStatusError arsenic e:
raise HTTPException(
status_code=e.response.status_code,
detail=f"NPS API error: {e.response.text}"
)
isolated from Exception arsenic e:
raise HTTPException(
status_code=500,
detail=f"Internal server error: {str(e)}"
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
To trial nan app, tally nan pursuing bid successful nan terminal:
Once nan server is running, unfastened your browser and spell to: http://localhost:8000/docs. This will unfastened an interface wherever we tin trial our API endpoint
- Click connected nan “Try it out” button.
- In nan park_code parameter field, participate “ca” (for California parks).
- Click “Execute”.
You should person a 200 OK consequence on pinch a JSON payload containing alert accusation for nationalist parks successful California.
To do this, adhd nan pursuing codification just before nan if __name__ == “__main__”: artifact successful your app.py file:
mcp = FastApiMCP(
app,
# Optional parameters
name="National Park Alerts API",
description="API for retrieving alerts from National Parks",
base_url="http://localhost:8000",
)
mcp.mount()
.
Alternatively, you tin transcript nan pursuing codification and switch your app.py pinch nan same:
from fastapi import FastAPI, HTTPException, Query
from typing import List, Optional
import httpx
import os
from dotenv import load_dotenv
from fastapi_mcp import FastApiMCP
# Load situation variables from .env file
load_dotenv()
app = FastAPI(title="National Park Alerts API")
# Get API cardinal from situation variable
NPS_API_KEY = os.getenv("NPS_API_KEY")
if not NPS_API_KEY:
raise ValueError("NPS_API_KEY situation adaptable is not set")
@app.get("/alerts")
async def get_alerts(
parkCode: Optional[str] = Query(None, description="Park codification (e.g., 'yell' for Yellowstone)"),
stateCode: Optional[str] = Query(None, description="State codification (e.g., 'wy' for Wyoming)"),
q: Optional[str] = Query(None, description="Search term")
):
"""
Retrieve parkland alerts from nan National Park Service API
"""
url = "https://developer.nps.gov/api/v1/alerts"
params = {
"api_key": NPS_API_KEY
}
# Add optional parameters if provided
if parkCode:
params["parkCode"] = parkCode
if stateCode:
params["stateCode"] = stateCode
if q:
params["q"] = q
try:
async pinch httpx.AsyncClient() arsenic client:
consequence = await client.get(url, params=params)
response.raise_for_status()
return response.json()
isolated from httpx.HTTPStatusError arsenic e:
raise HTTPException(
status_code=e.response.status_code,
detail=f"NPS API error: {e.response.text}"
)
isolated from Exception arsenic e:
raise HTTPException(
status_code=500,
detail=f"Internal server error: {str(e)}"
)
mcp = FastApiMCP(
app,
# Optional parameters
name="National Park Alerts API",
description="API for retrieving alerts from National Parks",
base_url="http://localhost:8000",
)
mcp.mount()
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Next, you’ll request to registry your FastAPI MCP server successful Cursor.
- Open Cursor and navigate to:
File > Preferences > Cursor Settings > MCP > Add a caller world MCP server
- This will unfastened nan mcp.json configuration file.
- Inside that file, adhd nan pursuing introduction and prevention it:
{
"mcpServers": {
"National Park Service": {
"command": "mcp-proxy",
"args": ["http://127.0.0.1:8000/mcp"]
}
}
}
Now tally nan app utilizing nan pursuing command:
Once nan app is running, navigate to File > Preferences > Cursor Settings > MCP. You should now spot your recently added server listed and moving nether nan MCP section.
You tin now trial nan server by entering a punctual successful nan chat. It will usage our MCP server to fetch and return nan due result.
Also, don’t hide to travel america on Twitter and subordinate our Telegram Channel and LinkedIn Group. Don’t Forget to subordinate our 90k+ ML SubReddit.
🔥 [Register Now] miniCON Virtual Conference connected AGENTIC AI: FREE REGISTRATION + Certificate of Attendance + 4 Hour Short Event (May 21, 9 am- 1 p.m. PST) + Hands connected Workshop

I americium a Civil Engineering Graduate (2022) from Jamia Millia Islamia, New Delhi, and I person a keen liking successful Data Science, particularly Neural Networks and their exertion successful various areas.