Rendere robuste le chiamate agli strumenti API
In produzione, lo strumento convert_currency() del currency server non dovrebbe bloccarsi se l'API dei tassi di cambio è lenta o irraggiungibile. Per mitigare questo rischio, implementerai un timeout nella richiesta e farai in modo che qualsiasi errore restituisca all'utente un messaggio breve e chiaro, invece di un'eccezione grezza.
Un server MCP è già stato istanziato e salvato nella variabile mcp.
Questo esercizio fa parte del corso
Introduzione al Model Context Protocol (MCP)
Istruzioni dell'esercizio
- Implementa una logica try-except che tenti la richiesta all'API e, in caso di errore, esegua un fail in modo pulito catturando l'eccezione.
- Aggiungi un timeout di 10 secondi alla chiamata
requests.get()in modo che la richiesta non resti bloccata indefinitamente.
esercizio interattivo pratico
Prova questo esercizio completando questo codice di esempio.
@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"))