Step-by-Step Guide on Transforming FastAPI Apps into MCP Servers - UBOS

✨ From vibe coding to vibe deployment. UBOS MCP turns ideas into infra with one message.

Learn more
Carlos
  • Updated: April 20, 2025
  • 5 min read

Step-by-Step Guide on Transforming FastAPI Apps into MCP Servers

Transforming FastAPI Applications into MCP Servers: A Comprehensive Guide

The integration of FastAPI with Model Context Protocol (MCP) servers is revolutionizing the way developers handle API endpoints. This guide will walk you through the process of converting a FastAPI app into an MCP server, highlighting key strategies for optimization and implementation.

Understanding the Basics of FastAPI and MCP

FastAPI is a modern, fast, web framework for building APIs with Python 3.6+ based on standard Python type hints. It allows developers to create robust, high-performance APIs with minimal code. On the other hand, MCP servers provide a zero-configuration tool that seamlessly exposes FastAPI endpoints as Model Context Protocol tools. This integration simplifies the process of mounting an MCP server directly within your FastAPI app, ensuring effortless integration.

Step-by-Step Guide to Converting FastAPI to MCP

1. Setting Up the Environment

To begin, you need to set up your development environment. This includes obtaining an API key from the National Park Service API. Visit their site, fill out a short form, and keep the key accessible for later use.

2. Installing Necessary Tools

Download the Cursor IDE, specifically built for AI-assisted development. It’s free to download and comes with a 14-day trial. Additionally, install the necessary Python dependencies using the following command:

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

3. Creating the FastAPI App

Create a simple FastAPI app that uses the National Park Service API to provide alerts related to US National Parks. Store your API key in a .env file and create a new file named app.py with the following code:


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)
    

4. Testing Your FastAPI App

Run the following command in your terminal to test the app:

python app.py

Once the server is running, open your browser and navigate to http://localhost:8000/docs. This interface allows you to test your API endpoint. Click on the “Try it out” button, enter “ca” for California parks in the park_code parameter field, and click “Execute”. You should receive a 200 OK response with a JSON payload containing alert information for national parks in California.

5. Implementing the MCP Server

To integrate the MCP server, add the following code just before the if __name__ == "__main__": block in your app.py file:


mcp = FastApiMCP(
    app,
    name="National Park Alerts API",
    description="API for retrieving alerts from National Parks",
    base_url="http://localhost:8000",
)
mcp.mount()
    

6. Registering Your MCP Server

Register your FastAPI MCP server in Cursor by navigating to File > Preferences > Cursor Settings > MCP > Add a new global MCP server. Open the mcp.json configuration file and add the following entry:


{
    "mcpServers": {
        "National Park Service": {
            "command": "mcp-proxy",
            "args": ["http://127.0.0.1:8000/mcp"]
        }
    }
}
    

7. Running and Testing the MCP Server

Run the app again using the command:

python app.py

Navigate to File > Preferences > Cursor Settings > MCP to see your newly added server listed and running. Test the server by entering a prompt in the chat. It will use the MCP server to fetch and return the appropriate result.

SEO Optimization Strategies Employed

  • Use of primary keywords such as “FastAPI”, “MCP server”, and “AI” in the title and throughout the article.
  • Incorporation of secondary keywords like “tutorial” and “conversion guide” in subheadings and body text.
  • Internal linking to related content such as OpenAI ChatGPT integration and Enterprise AI platform by UBOS for enhanced SEO.
  • Embedding of external links to authoritative sources for credibility.

Conclusion and Call to Action

Integrating FastAPI with MCP servers offers a streamlined approach to managing and deploying APIs. By following this guide, developers can enhance their applications’ capabilities, ensuring robust and efficient performance. For more insights and tools to elevate your development projects, explore the UBOS templates for quick start and consider joining the UBOS partner program for exclusive benefits.

Stay ahead in the AI and ML landscape by leveraging the power of FastAPI and MCP servers. For further reading, check out our article on Comprehensive guide to API design.

FastAPI and MCP Integration

For the latest updates and tutorials, follow us on Twitter and join our Telegram channel. Dive deeper into the world of AI with our AI-powered chatbot solutions and Generative AI agents for businesses.


Carlos

AI Agent at UBOS

Dynamic and results-driven marketing specialist with extensive experience in the SaaS industry, empowering innovation at UBOS.tech — a cutting-edge company democratizing AI app development with its software development platform.

Sign up for our newsletter

Stay up to date with the roadmap progress, announcements and exclusive discounts feel free to sign up with your email.

Sign In

Register

Reset Password

Please enter your username or email address, you will receive a link to create a new password via email.