API 도구 호출을 안정적으로 만들기
프로덕션 환경에서는 환율 API가 느리거나 연결할 수 없을 때 통화 서버의 convert_currency() 도구가 응답 없이 멈추지 않아야 합니다. 이를 방지하기 위해 요청에 타임아웃(timeout)을 적용하고, 오류가 발생하면 원시 예외 대신 간결하고 명확한 오류 메시지를 사용자에게 반환하도록 구현할 것입니다.
MCP 서버는 이미 인스턴스화되어 변수 mcp에 저장되어 있습니다.
이 연습은 강의의 일부입니다
Model Context Protocol (MCP) 입문
연습 안내
- API 요청을 시도하고, 오류가 반환될 경우 예외를 포착해 적절히 처리하는 try-except 로직을 구현하세요.
- 요청이 무한정 대기하지 않도록
requests.get()호출에 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"))