您是否遇到過這樣的情況:您希望聊天機器人使用一個工具,然後回答您的問題?聽起來很複雜,對吧!但是現在,MCP(模型上下文協議)為您提供了一種將 LLM 與外部工具輕鬆整合的方法,LLM 將能夠以各種方式使用這些工具。在本教程中,我們將深入探討如何使用 FastAPI-MCP 轉換一個由 MCP 伺服器驅動的使用 FastAPI 製作的簡單網路應用程式。
使用MCP的FastAPI
FastAPI 是一個非常簡單的 Python 工具,可幫助您使用 API 構建網路應用程式。它設計得既簡單易用又快速。將 FastAPI 想象成一個聰明的服務員,他接收您的點單(HTTP 請求),前往廚房(資料庫/伺服器),然後接收您的點單(輸出),然後將其顯示給您。它是構建網路後端、移動應用程式服務等的絕佳工具。
MCP 是 Anthropic 的一個開放標準協議,它為 LLM 提供了與外部資料來源和工具通訊的功能。可以將 MCP 視為一個工具包,為特定任務提供合適的工具。我們將使用 MCP 建立伺服器。
現在,如果將這些功能賦予您的 LLM 呢?這將使您的生活更加輕鬆!這就是為什麼FastAPI與MCP的整合可以提供很大幫助。FastAPI 負責不同來源的服務,而 MCP 則負責 LLM 的上下文。透過將 FastAPI 與 MCP 伺服器結合使用,我們可以訪問部署在網路上的所有工具,並將其用作 LLM 工具,使 LLM 更有效地開展工作。
Source: Cloudflare
什麼是FastAPI-MCP?
FastAPI-MCP是一種工具,它可以讓您將任何FastAPI應用程式轉換成像 ChatGPT 或Claude這樣的LLM可以理解並輕鬆使用的工具。透過使用FastAPI-MCP,您可以對FastAPI端點進行包裝,使其成為利用LLM的人工智慧生態系統中的即插即用工具。
如果您想了解如何使用 MCP,請閱讀這篇文章:如何使用 MCP?
使用FastAPI-MCP可以將哪些API轉換為MCP?
使用FastAPI-MCP,任何FastAPI端點都可以轉換為LLM的MCP工具。這些端點應包括
- GET 端點:轉換為 MCP 資源。
- POST、PUT、DELETE 端點:轉換為 MCP 工具。
- 自定義實用功能:可新增為額外的 MCP 工具
FastAPI-MCP 是一個非常易於使用的庫,能自動發現這些端點並將其轉換為 MCP。它還保留了這些 API 的模式和文件。
FastAPI-MCP的實際操作
讓我們來看一個如何將 FastAPI 端點轉換為 MCP 伺服器的簡單示例。首先,我們將建立一個 FastAPI 端點,然後使用 fastapi-mcp
將其轉換為 MCP 伺服器 。
配置FastAPI
1. 安裝依賴項
安裝所需的依賴項,使系統相容。
pip install fastapi fastapi_mcp uvicorn mcp-proxy
2. 匯入所需的依賴項
新建一個名為“main.py”的檔案,然後在其中匯入以下依賴項。
from fastapi import FastAPI, HTTPException, Query import httpx from fastapi_mcp import FastApiMCP
3. 定義 FastAPI 應用程式
讓我們定義一個名為“Weather Updates API”的 FastAPI 應用程式。
app = FastAPI(title="Weather Updates API")
4. 定義路由和函式
現在,我們將為應用程式定義路由,表示哪個端點將執行哪個函式。在這裡,我們使用 weather.gov API(免費)製作一個天氣更新應用程式,不需要任何 API 金鑰。我們只需在 https://api.weather.gov/points/{lat},{lon} 中輸入正確的經緯度值即可。
我們定義了一個 get_weather 函式,該函式將州名或州程式碼作為引數,然後在 CITY_COORDINATES 字典中找到相應的座標,然後用這些座標點選基礎 URL。
# Predefined latitude and longitude for major cities (for simplicity) # In a production app, you could use a geocoding service like Nominatim or Google Geocoding API CITY_COORDINATES = { "Los Angeles": {"lat": 34.0522, "lon": -118.2437}, "San Francisco": {"lat": 37.7749, "lon": -122.4194}, "San Diego": {"lat": 32.7157, "lon": -117.1611}, "New York": {"lat": 40.7128, "lon": -74.0060}, "Chicago": {"lat": 41.8781, "lon": -87.6298}, # Add more cities as needed } @app.get("/weather") async def get_weather( stateCode: str = Query(..., description="State code (e.g., 'CA' for California)"), city: str = Query(..., description="City name (e.g., 'Los Angeles')") ): """ Retrieve today's weather from the National Weather Service API based on city and state """ # Get coordinates (latitude, longitude) for the given city if city not in CITY_COORDINATES: raise HTTPException( status_code=404, detail=f"City '{city}' not found in predefined list. Please use another city." ) coordinates = CITY_COORDINATES[city] lat, lon = coordinates["lat"], coordinates["lon"] # URL for the NWS API Gridpoints endpoint base_url = f"https://api.weather.gov/points/{lat},{lon}" try: async with httpx.AsyncClient() as client: # First, get the gridpoint information for the given location gridpoint_response = await client.get(base_url) gridpoint_response.raise_for_status() gridpoint_data = gridpoint_response.json() # Retrieve the forecast data using the gridpoint information forecast_url = gridpoint_data["properties"]["forecast"] forecast_response = await client.get(forecast_url) forecast_response.raise_for_status() forecast_data = forecast_response.json() # Returning today's forecast today_weather = forecast_data["properties"]["periods"][0] return { "city": city, "state": stateCode, "date": today_weather["startTime"], "temperature": today_weather["temperature"], "temperatureUnit": today_weather["temperatureUnit"], "forecast": today_weather["detailedForecast"], } except httpx.HTTPStatusError as e: raise HTTPException( status_code=e.response.status_code, detail=f"NWS API error: {e.response.text}" ) except Exception as e: raise HTTPException( status_code=500, detail=f"Internal server error: {str(e)}" )
5. 設定MCP伺服器
現在讓我們使用 fastapi-mcp 庫將 FastAPI 應用程式轉換為 MCP。這個過程非常簡單,我們只需新增幾行程式碼,fastapi-mcp 就會自動將端點轉換為 MCP 工具,並輕鬆檢測其模式和文件。
mcp = FastApiMCP( app, name="Weather Updates API", description="API for retrieving today's weather from weather.gov", ) mcp.mount()
6. 啟動應用程式
現在,在 Python 檔案末尾新增以下內容。
if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)
然後轉到終端,執行 main.py 檔案。
python main.py
現在,您的 FastAPI 應用程式應能在 localhost 中成功啟動。
配置Cursor
讓我們配置用於測試 MCP 伺服器的 Cursor IDE。
- 從此處下載 Cursor:https://www.cursor.com/downloads。
- 安裝後,註冊並進入主螢幕。
- 現在從頂部工具欄進入 File,點選 Preferences,然後點選 Cursor Settings。
- 在 Cursor 設定中,點選 MCP。
- 在 MCP 選項卡上,點選 Add new global MCP Server,然後開啟一個 mcp.json 檔案。貼上以下程式碼並儲存檔案。
{ "mcpServers": { "National Park Service": { "command": "mcp-proxy", "args": ["http://127.0.0.1:8000/mcp"] } } }
- 回到 Cursor Settings,您應該看到以下內容:
如果你在螢幕上看到這個,說明你的伺服器已成功執行並連線到 Cursor IDE。如果顯示錯誤,請嘗試使用右上角的重啟按鈕。
我們已經在 Cursor IDE 中成功設定了 MCP 伺服器。現在,讓我們測試一下伺服器。
測試MCP伺服器
我們的 MCP 伺服器可以檢索天氣更新。我們只需向 Cursor IDE 詢問任何地點的天氣更新,它就會使用 MCP 伺服器為我們獲取。
查詢:“Please tell me what is today’s weather in San Diego”
查詢:“New York weather?”
從輸出結果可以看出,我們的 MCP 伺服器執行良好。我們只需詢問天氣詳情,它就會自行決定是否使用 MCP 伺服器。在第二個輸出中,我們含糊地問了 “紐約天氣如何?”它就能根據我們之前的提示瞭解到查詢的上下文,並使用適當的 MCP 工具進行回答。
小結
MCP 允許 LLM 透過訪問外部工具來提高其回答能力,而 FastAPI 則提供了一種簡單的方法來實現這一點。在本綜合指南中,我們使用 fastapi-mcp 庫將這兩種技術結合起來。利用這個庫,我們可以將任何 API 轉換為 MCP 伺服器,這將有助於 LLM 和人工智慧代理從 API 獲取最新資訊。無需為每項新任務定義自定義工具。帶有 FastAPI 的 MCP 將自動處理一切。MCP的引入帶來了LLM的革命,而現在,FastAPI與MCP的搭配正在徹底改變LLM訪問這些工具的方式。
評論留言