定義 MCP 伺服器資源
你正在擴充用於貨幣換算的 MCP 伺服器,讓它能存取你所用 API 支援的貨幣清單。European Central Bank 會發布一份貨幣代碼清單,存放在伺服器目錄中的 currencies.txt 檔案。用戶端可以利用這份清單,確保 LLM 傳給工具函式的引數值是正確的。
你的任務是定義一個名為 get_currencies() 的 MCP 資源,讀取 currencies.txt 的內容。
本練習屬於課程
Model Context Protocol(MCP)入門
練習說明
- 使用正確的裝飾器與
"file://currencies.txt"這個 URI,將get_currencies()函式轉成資源。 - 完成
get_currencies()函式,開啟並讀取currencies.txt檔案的內容。 - 印出呼叫
get_currencies()的結果,驗證此資源能正確運作。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Currency Converter")
# Define a resource for the currencies file
____
def get_currencies() -> str:
"""
Get the list of currency names published by the European Central Bank for currency conversion.
Returns:
Contents of the currencies.txt file with currency names
"""
# Open currencies.txt and read the data
try:
with open('____', 'r') as f:
content = f.____
return content
except FileNotFoundError:
return "currencies.txt file not found"
# Test the resource function
print(____)