將資料庫作為資源
接下來把這些資料庫資訊,作為資源提供給 MCP 伺服器使用。這可以用在後續流程中,驗證 LLM 請求的貨幣代碼是否受支援,或是在使用者介面中,將貨幣代碼做成下拉選單或自動完成的選項。
資料庫仍為 currencies.db,建立伺服器的程式碼也已為你準備好。
本練習屬於課程
Model Context Protocol(MCP)入門
練習說明
- 建立與資料庫(
currencies.db)的連線。 - 為該資料庫連線建立一個新的 MCP 伺服器資源。
- 執行資料庫查詢,讓
get_currencies()函式回傳資料庫內容。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Currency Converter")
# Connect to the database on startup
conn = sqlite3.____("____")
conn.row_factory = sqlite3.Row
# Create an MCP resource
@mcp.____("db://currencies")
def get_currencies() -> str:
"""
Get the list of currency names published by the European Central Bank for currency conversion.
Returns:
One line per currency (code - name), from the database.
"""
try:
# Query the database
cursor = conn.____("SELECT code, name FROM currencies")
rows = cursor.fetchall()
return "\n".join(f"{row['code']} - {row['name']}" for row in rows)
except sqlite3.Error as e: return f"Error: {e}"
result = get_currencies()
print(result[:200] + "..." if len(result) > 200 else result)