CommencerCommencer gratuitement

Making API Tool Calls Robust

In production, the currency server's convert_currency() tool should not hang if the exchange-rate API is slow or unreachable. To mitigate this, you'll implement a timeout to the request and ensure any failure returns a short, clear error message to the user instead of a raw exception.

An MCP server has already been instantiated and stored as the variable mcp.

Cet exercice fait partie du cours

Introduction to Model Context Protocol (MCP)

Afficher le cours

Instructions

  • Implement try-except logic that will attempt the API request, and gracefully fail if an error is returned by capturing the exception.
  • Add a timeout of 10 seconds to the requests.get() call so the request does not hang indefinitely.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

@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"))
Modifier et exécuter le code