Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      In-House vs. Outsource Node.js Development Teams: 9 Key Differences for the C-Suite (2025)

      July 19, 2025

      Why Non-Native Content Designers Improve Global UX

      July 18, 2025

      DevOps won’t scale without platform engineering and here’s why your teams are still stuck

      July 18, 2025

      This week in AI dev tools: Slack’s enterprise search, Claude Code’s analytics dashboard, and more (July 18, 2025)

      July 18, 2025

      DistroWatch Weekly, Issue 1131

      July 20, 2025

      I ditched my Bluetooth speakers for this slick turntable – and it’s more practical than I thought

      July 19, 2025

      This split keyboard offers deep customization – if you’re willing to go all in

      July 19, 2025

      I spoke with an AI version of myself, thanks to Hume’s free tool – how to try it

      July 19, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The details of TC39’s last meeting

      July 20, 2025
      Recent

      The details of TC39’s last meeting

      July 20, 2025

      Simple wrapper for Chrome’s built-in local LLM (Gemini Nano)

      July 19, 2025

      Online Examination System using PHP and MySQL

      July 18, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Windows 11 tests “shared audio” to play music via multiple devices, new taskbar animations

      July 20, 2025
      Recent

      Windows 11 tests “shared audio” to play music via multiple devices, new taskbar animations

      July 20, 2025

      WhatsApp for Windows 11 is switching back to Chromium web wrapper from UWP/native

      July 20, 2025

      DistroWatch Weekly, Issue 1131

      July 20, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Machine Learning»Step by Step Guide on How to Convert a FastAPI App into an MCP Server

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

    April 20, 2025
    Step by Step Guide on How to Convert a FastAPI App into an MCP Server

    FastAPI-MCP is a zero-configuration tool that seamlessly exposes FastAPI endpoints as Model Context Protocol (MCP) tools. It allows you to mount an MCP server directly within your FastAPI app, making integration effortless.

    In this tutorial, we’ll explore how to use FastAPI-MCP by converting a FastAPI endpoint—which fetches alerts for U.S. national parks using the National Park Service API—into an MCP-compatible server. We’ll be working in Cursor IDE to walk through this setup step by step.

    Step 1: Setting up the environment

    National Park Service API

    To use the National Park Service API, you can request an API key by visiting this link and filling out a short form. Once submitted, the API key will be sent to your email.

    Make sure to keep this key accessible—we’ll be using it shortly.

    Cursor IDE Installation

    You can download the Cursor IDE from cursor.com. It is built specifically for AI-assisted development. It’s free to download and comes with a 14-day free trial.

    Python Dependencies

    Run the following command to download the required libraries:

    Copy CodeCopiedUse a different Browser
    pip install fastapi uvicorn httpx python-dotenv pydantic fastapi-mcp mcp-proxy

    Step 2: Creating the FastAPI app

    We will be creating a simple FastAPI app that uses the National Park Service API to give alerts related to US National Parks. Later we will convert this app into an MCP server. 

    First create a .env file and store your API key

    Copy CodeCopiedUse a different Browser
    NPS_API_KEY=<YOUR_API_KEY>

    Replace <YOUR_API_KEY> with the one you generated.Now, create a new file named app.py and paste the following code. This will serve as the core logic of your application:

    Copy CodeCopiedUse a different Browser
    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)

    Step 3: Testing the FastAPI app

    To test the app, run the following command in the terminal:

    Copy CodeCopiedUse a different Browser
    python app.py

    Once the server is running, open your browser and go to: http://localhost:8000/docs. This will open an interface where we can test our API endpoint

    1. Click on the “Try it out” button.
    2. In the park_code parameter field, enter “ca” (for California parks).
    3. Click “Execute”.

    You should receive a 200 OK response along with a JSON payload containing alert information for national parks in California.

    Step 4: MCP Server Implementation

    To do this, add the following code just before the if __name__ == “__main__”: block in your app.py file:

    Copy CodeCopiedUse a different Browser
    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 can copy the following code and replace your app.py with the same:

    Copy CodeCopiedUse a different Browser
    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’ll need to register your FastAPI MCP server in Cursor.

    1. Open Cursor and navigate to:
      File > Preferences > Cursor Settings > MCP > Add a new global MCP server
    2. This will open the mcp.json configuration file.
    3. Inside that file, add the following entry and save it:
    Copy CodeCopiedUse a different Browser
    {
        "mcpServers": {
          "National Park Service": {
              "command": "mcp-proxy",
              "args": ["http://127.0.0.1:8000/mcp"]
          }
        }
    }

    Step 5: Running the server

    Now run the app using the following command:

    Copy CodeCopiedUse a different Browser
    python app.py

    Once the app is running, navigate to  File > Preferences > Cursor Settings > MCP. You should now see your newly added server listed and running under the MCP section.

    You can now test the server by entering a prompt in the chat. It will use our MCP server to fetch and return the appropriate result.


    Also, don’t forget to follow us on Twitter and join our Telegram Channel and LinkedIn Group. Don’t Forget to join our 90k+ ML SubReddit.

    🔥 [Register Now] miniCON Virtual Conference on AGENTIC AI: FREE REGISTRATION + Certificate of Attendance + 4 Hour Short Event (May 21, 9 am- 1 pm PST) + Hands on Workshop

    The post Step by Step Guide on How to Convert a FastAPI App into an MCP Server appeared first on MarkTechPost.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleMeta AI Introduces Collaborative Reasoner (Coral): An AI Framework Specifically Designed to Evaluate and Enhance Collaborative Reasoning Skills in LLMs
    Next Article My Cup Size is Stanley Shirt

    Related Posts

    Machine Learning

    How to Evaluate Jailbreak Methods: A Case Study with the StrongREJECT Benchmark

    July 20, 2025
    Machine Learning

    Language Models Improve When Pretraining Data Matches Target Tasks

    July 18, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2025-48280 – AutomatorWP SQL Injection

    Common Vulnerabilities and Exposures (CVEs)

    Meta Teams Up with UK to Launch $1 Million Open Source AI Fellowship

    Operating Systems

    CVE-2025-31260 – Apple macOS Sequoia Permission Escalation Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-7504 – WordPress Friends Plugin PHP Object Injection Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    CVE-2025-6881 – D-Link jhttpd PPPoE Buffer Overflow Vulnerability

    June 29, 2025

    CVE ID : CVE-2025-6881

    Published : June 30, 2025, 2:15 a.m. | 44 minutes ago

    Description : A vulnerability was found in D-Link DI-8100 16.07.21. It has been rated as critical. Affected by this issue is some unknown functionality of the file /pppoe_base.asp of the component jhttpd. The manipulation of the argument mschap_en leads to buffer overflow. The attack may be launched remotely. The exploit has been disclosed to the public and may be used.

    Severity: 8.8 | HIGH

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    How to Quickly Fix Minecraft Realms 502 Bad Gateway Error

    May 21, 2025

    CVE-2025-4287 – PyTorch CUDA NCCL Denial of Service Vulnerability

    May 5, 2025

    What might Microsoft announce at its 50th anniversary Copilot event?

    April 3, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.