讓 API 工具呼叫更穩健
在正式環境中,若匯率 API 緩慢或無法連線,貨幣伺服器的 convert_currency() 工具不應該卡住。為了降低風險,你將在請求中加入逾時機制,並確保任何失敗都回傳簡短且清楚的錯誤訊息給使用者,而不是原始的例外。
一個 MCP 伺服器已建立並儲存為變數 mcp。
本練習屬於課程
Model Context Protocol(MCP)入門
練習說明
- 實作 try-except 邏輯:嘗試發送 API 請求,並在出現錯誤時捕捉例外,優雅地失敗處理。
- 在
requests.get()呼叫中加入 10 秒的 timeout,避免請求無限期卡住。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
@mcp.tool()
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
"""
Convert an amount from one currency to another using current exchange rates.
Args:
amount: The amount to convert
from_currency: Source currency code (e.g., 'USD', 'EUR', 'GBP')
to_currency: Target currency code (e.g., 'USD', 'EUR', 'GBP')
Returns:
A string with the conversion result and exchange rate
"""
url = f"https://api.frankfurter.dev/v1/latest?base={from_currency}&symbols={to_currency}"
# Implement try-except to gracefully handle errors
____:
# Add a 10-second timeout so the request does not hang
r = requests.get(url, ____=____)
r.raise_for_status()
data = r.json()
rate = data["rates"].get(to_currency)
if rate is None:
return f"Could not find exchange rate for {from_currency} to {to_currency}"
return f"{amount} {from_currency} = {amount * rate:.2f} {to_currency} (Rate: {rate})"
____ requests.exceptions.RequestException as e:
return f"Error converting currency: {e}"
print(convert_currency(10, "USD", "EUR"))