让 API 工具调用更健壮
在生产环境中,如果汇率 API 缓慢或不可达,货币服务器的 convert_currency() 工具不应一直挂起。为此,您将为请求实现一个超时,并确保任何失败都向用户返回简短清晰的错误信息,而不是原始异常。
一个 MCP 服务器已实例化并存储在变量 mcp 中。
本练习是课程的一部分
Model Context Protocol (MCP) 入门
练习说明
- 实现 try-except 逻辑:尝试发起 API 请求;一旦出错,捕获异常并优雅地失败。
- 在
requests.get()调用中添加 10 秒超时(timeout=10),避免请求无限期挂起。
交互式实操练习
通过完成这段示例代码来试试这个练习。
@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"))