Kom igångKom igång gratis

Gör API-verktygssanrop robusta

I produktion bör valutagatewayens convert_currency()-verktyg inte hänga sig om API:et för valutakurser är långsamt eller otillgängligt. För att hantera detta implementerar du en timeout för anropet och ser till att eventuella fel returnerar ett kort, tydligt felmeddelande till användaren i stället för ett rått undantag.

En MCP-server har redan instansierats och lagrats i variabeln mcp.

Den här övningen är en del av kursen

Introduktion till Model Context Protocol (MCP)

Visa kurs

Övningsinstruktioner

  • Implementera try-except-logik som försöker utföra API-anropet och hanterar eventuella fel på ett kontrollerat sätt genom att fånga undantaget.
  • Lägg till en timeout på 10 sekunder i anropet till requests.get() så att anropet inte hänger sig i oändlighet.

Interaktiv övning med praktiskt arbete

Testa den här övningen genom att slutföra den här exempelkoden.

@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"))
Redigera och kör kod