HomeArtificial IntelligenceStep by Step Information on Tips on how to Convert a FastAPI...

Step by Step Information on Tips on how to Convert a FastAPI App into an MCP Server


FastAPI-MCP is a zero-configuration software that seamlessly exposes FastAPI endpoints as Mannequin Context Protocol (MCP) instruments. It lets you mount an MCP server straight inside your FastAPI app, making integration easy.

On this tutorial, we’ll discover how one can use FastAPI-MCP by changing a FastAPI endpoint—which fetches alerts for U.S. nationwide parks utilizing the Nationwide Park Service API—into an MCP-compatible server. We’ll be working in Cursor IDE to stroll by this setup step-by-step.

Nationwide Park Service API

To make use of the Nationwide Park Service API, you’ll be able to request an API key by visiting this hyperlink and filling out a brief kind. As soon as submitted, the API key might be despatched to your e mail.

Be certain that to maintain this key accessible—we’ll be utilizing it shortly.

Cursor IDE Set up

You’ll be able to obtain the Cursor IDE from cursor.com. It’s constructed particularly for AI-assisted growth. It’s free to obtain and comes with a 14-day free trial.

Python Dependencies

Run the next command to obtain the required libraries:

pip set up fastapi uvicorn httpx python-dotenv pydantic fastapi-mcp mcp-proxy

We might be making a easy FastAPI app that makes use of the Nationwide Park Service API to present alerts associated to US Nationwide Parks. Later we are going to convert this app into an MCP server. 

First create a .env file and retailer your API key

Exchange with the one you generated.Now, create a brand new file named app.py and paste the next code. This can function the core logic of your software:

from fastapi import FastAPI, HTTPException, Question
from typing import Checklist, Non-obligatory
import httpx
import os
from dotenv import load_dotenv
from fastapi_mcp import FastApiMCP


# Load atmosphere variables from .env file
load_dotenv()

app = FastAPI(title="Nationwide Park Alerts API")


# Get API key from atmosphere variable
NPS_API_KEY = os.getenv("NPS_API_KEY")
if not NPS_API_KEY:
    increase ValueError("NPS_API_KEY atmosphere variable shouldn't be set")

@app.get("/alerts")
async def get_alerts(
    parkCode: Non-obligatory[str] = Question(None, description="Park code (e.g., 'yell' for Yellowstone)"),
    stateCode: Non-obligatory[str] = Question(None, description="State code (e.g., 'wy' for Wyoming)"),
    q: Non-obligatory[str] = Question(None, description="Search time period")
):
    """
    Retrieve park alerts from the Nationwide Park Service API
    """
    url = "https://developer.nps.gov/api/v1/alerts"
    params = {
        "api_key": NPS_API_KEY
    }
   
    # Add optionally available parameters if offered
    if parkCode:
        params["parkCode"] = parkCode
    if stateCode:
        params["stateCode"] = stateCode
    if q:
        params["q"] = q
   
    strive:
        async with httpx.AsyncClient() as consumer:
            response = await consumer.get(url, params=params)
            response.raise_for_status()
            return response.json()
    besides httpx.HTTPStatusError as e:
        increase HTTPException(
            status_code=e.response.status_code,
            element=f"NPS API error: {e.response.textual content}"
        )
    besides Exception as e:
        increase HTTPException(
            status_code=500,
            element=f"Inside server error: {str(e)}"
        )


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

To check the app, run the next command within the terminal:

As soon as the server is operating, open your browser and go to: http://localhost:8000/docs. This can open an interface the place we are able to check our API endpoint

  1. Click on on the “Attempt it out” button.
  2. Within the park_code parameter discipline, enter “ca” (for California parks).
  3. Click on “Execute”.

It’s best to obtain a 200 OK response together with a JSON payload containing alert info for nationwide parks in California.

To do that, add the next code simply earlier than the if __name__ == “__main__”: block in your app.py file:

mcp = FastApiMCP(
    app,
    # Non-obligatory parameters
    title="Nationwide Park Alerts API",
    description="API for retrieving alerts from Nationwide Parks",
    base_url="http://localhost:8000",
)
mcp.mount()

.

Alternatively, you’ll be able to copy the next code and change your app.py with the identical:

from fastapi import FastAPI, HTTPException, Question
from typing import Checklist, Non-obligatory
import httpx
import os
from dotenv import load_dotenv
from fastapi_mcp import FastApiMCP


# Load atmosphere variables from .env file
load_dotenv()

app = FastAPI(title="Nationwide Park Alerts API")


# Get API key from atmosphere variable
NPS_API_KEY = os.getenv("NPS_API_KEY")
if not NPS_API_KEY:
    increase ValueError("NPS_API_KEY atmosphere variable shouldn't be set")

@app.get("/alerts")
async def get_alerts(
    parkCode: Non-obligatory[str] = Question(None, description="Park code (e.g., 'yell' for Yellowstone)"),
    stateCode: Non-obligatory[str] = Question(None, description="State code (e.g., 'wy' for Wyoming)"),
    q: Non-obligatory[str] = Question(None, description="Search time period")
):
    """
    Retrieve park alerts from the Nationwide Park Service API
    """
    url = "https://developer.nps.gov/api/v1/alerts"
    params = {
        "api_key": NPS_API_KEY
    }
   
    # Add optionally available parameters if offered
    if parkCode:
        params["parkCode"] = parkCode
    if stateCode:
        params["stateCode"] = stateCode
    if q:
        params["q"] = q
   
    strive:
        async with httpx.AsyncClient() as consumer:
            response = await consumer.get(url, params=params)
            response.raise_for_status()
            return response.json()
    besides httpx.HTTPStatusError as e:
        increase HTTPException(
            status_code=e.response.status_code,
            element=f"NPS API error: {e.response.textual content}"
        )
    besides Exception as e:
        increase HTTPException(
            status_code=500,
            element=f"Inside server error: {str(e)}"
        )

mcp = FastApiMCP(
    app,
    # Non-obligatory parameters
    title="Nationwide Park Alerts API",
    description="API for retrieving alerts from Nationwide Parks",
    base_url="http://localhost:8000",
)
mcp.mount()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Subsequent, you’ll must register your FastAPI MCP server in Cursor.

  1. Open Cursor and navigate to:
    File > Preferences > Cursor Settings > MCP > Add a brand new world MCP server
  2. This can open the mcp.json configuration file.
  3. Inside that file, add the next entry and put it aside:
{
    "mcpServers": {
      "Nationwide Park Service": {
          "command": "mcp-proxy",
          "args": ["http://127.0.0.1:8000/mcp"]
      }
    }
}

Now run the app utilizing the next command:

As soon as the app is operating, navigate to  File > Preferences > Cursor Settings > MCP. It’s best to now see your newly added server listed and operating below the MCP part.

Now you can check the server by coming into a immediate within the chat. It would use our MCP server to fetch and return the suitable outcome.


Additionally, don’t overlook to comply with us on Twitter and be a part of our Telegram Channel and LinkedIn Group. Don’t Neglect to affix our 90k+ ML SubReddit.

🔥 [Register Now] miniCON Digital Convention on AGENTIC AI: FREE REGISTRATION + Certificates of Attendance + 4 Hour Quick Occasion (Could 21, 9 am- 1 pm PST) + Fingers on Workshop


I’m a Civil Engineering Graduate (2022) from Jamia Millia Islamia, New Delhi, and I’ve a eager curiosity in Knowledge Science, particularly Neural Networks and their software in numerous areas.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments