MarkTechPost@AI 前天 14:00
Step by Step Guide on How to Convert a FastAPI App into an MCP Server
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文详细介绍了如何使用 FastAPI-MCP 工具,将一个 FastAPI 应用转换为 MCP(Model Context Protocol)服务器。通过一个实际案例,将用于获取美国国家公园警报的 FastAPI 接口,转换为 MCP 兼容的服务器。文章涵盖了环境设置、FastAPI 应用创建、测试以及 MCP 服务器的实现,并提供了在 Cursor IDE 中配置和运行服务器的步骤。最终,用户可以在 Cursor IDE 中通过聊天方式测试和使用这个 MCP 服务器。

💡 FastAPI-MCP 是一个零配置工具,能将 FastAPI 接口无缝转换为 MCP 工具。

🔑 要使用 FastAPI-MCP,首先需要安装必要的依赖库,包括 fastapi、uvicorn、httpx、python-dotenv、pydantic 和 fastapi-mcp。

🏞️ 示例应用通过调用国家公园管理局 API 获取警报信息,应用代码中包含了从 .env 文件加载 API 密钥,以及定义 `/alerts` 接口,支持 parkCode、stateCode 和 q 参数查询。

⚙️ 将 FastAPI 应用转换为 MCP 服务器,需要在 `app.py` 中添加 `FastApiMCP` 的配置,并将其挂载到 FastAPI 应用上,指定服务器名称、描述和基础 URL。

💻 在 Cursor IDE 中,需要在设置中添加 MCP 服务器配置,指定服务器名称、启动命令和参数,然后运行应用,即可通过 Cursor 的聊天功能测试 MCP 服务器。

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:

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

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:

from fastapi import FastAPI, HTTPException, Queryfrom typing import List, Optionalimport httpximport osfrom dotenv import load_dotenvfrom fastapi_mcp import FastApiMCP# Load environment variables from .env fileload_dotenv()app = FastAPI(title="National Park Alerts API")# Get API key from environment variableNPS_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:

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

    Click on the “Try it out” button.
    In the park_code parameter field, enter “ca” (for California parks).
    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:

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:

from fastapi import FastAPI, HTTPException, Queryfrom typing import List, Optionalimport httpximport osfrom dotenv import load_dotenvfrom fastapi_mcp import FastApiMCP# Load environment variables from .env fileload_dotenv()app = FastAPI(title="National Park Alerts API")# Get API key from environment variableNPS_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.

    Open Cursor and navigate to:
    File > Preferences > Cursor Settings > MCP > Add a new global MCP server
    This will open the mcp.json configuration file.
    Inside that file, add the following entry and save it:
{    "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:

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.

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

FastAPI MCP Python API Cursor IDE
相关文章