AI

Step by Step Guide on How to Convert a FastAPI App into an MCP Server

Fastapi-mcp It is the zero composition tool that is smoothly revealing Fastapi Form Context Protocol (MCP) tools. It allows you to install the MCP server directly within your Fastapi application, making integration effortlessly.

In this tutorial, we will explore how to use Fastapi-MCP by converting the Fastapi-ending point that brings alerts to the US National Gardens using the National Park Service-to a MCP server. We will work in IDE index To go through this step by step.

National Park Service applications interface

To use the National Park Service applications interface, you can order the API key by visiting this link and filling a short model. Once it is sent, the API key will be sent to your email.

Make sure to keep this key available – we will use it soon.

IDE installation

You can download IDE index From Cursor.com. Designed specifically for development with the help of AI. It is free to download and comes with a file 14 days free experience.

The consequences are Bethon

Run the following order to download the required libraries:

pip install fastapi uvicorn httpx python-dotenv pydantic fastapi-mcp mcp-proxy

We will create a simple Fastapi application that uses the National Park Service application to give alerts related to US national parks. Later we will convert this app into a MCP server.

First, create. ENV file and store your API key

Replace Using this product you created. Now, create a new file called App.PY and paste the next code. This will be the basic 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 environment variables from .env file
load_dotenv()

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


# Get API key from environment variable
NPS_API_KEY = os.getenv("NPS_API_KEY")
if not NPS_API_KEY:
    raise ValueError("NPS_API_KEY environment variable is not set")

@app.get("/alerts")
async def get_alerts(
    parkCode: Optional[str] = Query(None, description="Park code (e.g., 'yell' for Yellowstone)"),
    stateCode: Optional[str] = Query(None, description="State code (e.g., 'wy' for Wyoming)"),
    q: Optional[str] = Query(None, description="Search term")
):
    """
    Retrieve park alerts from the 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 with httpx.AsyncClient() as client:
            response = await client.get(url, params=params)
            response.raise_for_status()
            return response.json()
    except httpx.HTTPStatusError as e:
        raise HTTPException(
            status_code=e.response.status_code,
            detail=f"NPS API error: {e.response.text}"
        )
    except Exception as 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 test the application, run the next thing at the station:

Once the server turns, open your browser and go to: http: // Localhost: 8000/docs. This will open an interface where we can test the end point of our application programming interface

  1. Click on “Try it” button.
  2. In the Park_Code teacher field, enter “CA” (for California Gardens).
  3. Click “Extends”.

You should receive a 200 OK response along with the JSON to the California National Gardens.

To do this, add the following symbol Before If ___Name__ == “__main__”: Block 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()

.

Instead, you can copy the next code and replace you App.py With the 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 environment variables from .env file
load_dotenv()

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


# Get API key from environment variable
NPS_API_KEY = os.getenv("NPS_API_KEY")
if not NPS_API_KEY:
    raise ValueError("NPS_API_KEY environment variable is not set")

@app.get("/alerts")
async def get_alerts(
    parkCode: Optional[str] = Query(None, description="Park code (e.g., 'yell' for Yellowstone)"),
    stateCode: Optional[str] = Query(None, description="State code (e.g., 'wy' for Wyoming)"),
    q: Optional[str] = Query(None, description="Search term")
):
    """
    Retrieve park alerts from the 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 with httpx.AsyncClient() as client:
            response = await client.get(url, params=params)
            response.raise_for_status()
            return response.json()
    except httpx.HTTPStatusError as e:
        raise HTTPException(
            status_code=e.response.status_code,
            detail=f"NPS API error: {e.response.text}"
        )
    except Exception as 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 will need to register the Fastapi MCP server in the index.

  1. Open indicator and move to:
    File> Preferences> Index settings> MCP> Add a new global MCP server
  2. This will open the MCP.json formation file.
  3. Inside this file, add the next input and save it:
{
    "mcpServers": {
      "National Park Service": {
          "command": "mcp-proxy",
          "args": ["http://127.0.0.1:8000/mcp"]
      }
    }
}

Now run the application using the following command:

Once the application is run, go to file> Preferences> Index settings> MCP. You should now see the newly added server and run it within the MCP section.

You can now test the server by entering a router in the chat. Our MCP server will use to bring the right result and return it.


Also, do not forget to follow us twitter And join us Telegram channel and LinkedIn GrOup. Don’t forget to join 90k+ ml subreddit.

🔥 [Register Now] The virtual Minicon Conference on Agency AI: Free Registration + attendance Certificate + 4 hours short (May 21, 9 am- Pacific time)


I am a graduate of civil engineering (2022) from Islamic Melia, New Delhi, and I have a strong interest in data science, especially nervous networks and their application in various fields.

Don’t miss more hot News like this! Click here to discover the latest in AI news!

2025-04-20 05:56:00

Related Articles

Back to top button