加入 Docstring 與型別註記
現在要透過 docstring 與型別註記(type hints),讓你的 convert_currency() 工具更容易被 LLM 使用。沒有這些說明,LLM 可能無法有效選擇要呼叫的工具,或把不正確的值傳入引數——兩者都會造成應用程式表現不穩定!
一個 MCP 伺服器已使用 FastMCP 建立並指派給 mcp。
本練習屬於課程
Model Context Protocol(MCP)入門
練習說明
- 為函式引數與回傳物件加入合適的型別。
- 完成 docstring,將三個函式引數與其定義正確對應。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Adding typing to the function arguments and return object
@mcp.tool()
def convert_currency(amount: ____, from_currency: ____, to_currency: ____) -> ____:
# Complete the docstring with the function arguments
"""
Convert an amount from one currency to another using current exchange rates.
Args:
____: The amount to convert
____: Source currency code (e.g., 'USD', 'EUR', 'GBP')
____: 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}"
response = requests.get(url)
data = response.json()
rate = data['rates'].get(to_currency)
if rate is None:
return f"Could not find exchange rate for {from_currency} to {to_currency}"
converted_amount = amount * rate
return f"{amount} {from_currency} = {converted_amount:.2f} {to_currency} (Rate: {rate})"
print(convert_currency(amount=100, from_currency="EUR", to_currency="USD"))