Zacznij terazZacznij za darmo

Twój pierwszy serwer MCP

Czas na praktykę z pierwszym serwerem MCP! Cały kod jest już dla ciebie przygotowany – nauczysz się go pisać w następnym filmie, ale już teraz przyjrzyj się jego strukturze:

  1. Instancja serwera MCP jest definiowana za pomocą FastMCP()
  2. Funkcja narzędziowa (convert_currency()) wykonuje określone działanie – w tym przypadku pobiera informacje o kursach walut z Frankfurter API.
  3. Funkcja jest przekształcana w narzędzie MCP przy użyciu dekoratora @mcp.tool().

To ćwiczenie jest częścią kursu

Wprowadzenie do Model Context Protocol (MCP)

Zobacz kurs

Instrukcje do ćwiczenia

  • Przejrzyj dostarczony kod, aby zobaczyć, jak funkcja jest przekształcana w narzędzie serwera MCP.
  • W linii 43 przetestuj narzędzie MCP, podając kwotę oraz wybrane przez siebie kody walut źródłowej i docelowej.

Uwaga: Używaj oficjalnych kodów walut, np. GBP dla funta szterlinga.

Interaktywne ćwiczenie praktyczne

Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.

# Create an MCP server instance
mcp = FastMCP("Currency Converter")

@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
    """
    # API endpoint for Frankfurter
    url = f"https://api.frankfurter.dev/v1/latest?base={from_currency}&symbols={to_currency}"

    try:
        # Make the API request
        response = requests.get(url)
        response.raise_for_status()

        # Parse the response
        data = response.json()

        # Get the exchange rate
        rate = data['rates'].get(to_currency)

        if rate is None:
            return f"Could not find exchange rate for {from_currency} to {to_currency}"

        # Calculate the converted amount
        converted_amount = amount * rate

        return f"{amount} {from_currency} = {converted_amount:.2f} {to_currency} (Rate: {rate})"

    except requests.exceptions.RequestException as e:
        return f"Error converting currency: {str(e)}"

print("Testing Currency Converter:")
result = convert_currency(amount=100, from_currency="USD", to_currency="EUR")
print(result)
Edytuj i uruchom kod