EmpezarEmpieza gratis

Tu primer servidor MCP

¡Hora de ensuciarte las manos con tu primer servidor MCP! Aquí te damos todo el código, que explicaremos en el próximo vídeo, pero echa un vistazo al flujo del código:

  1. Se define una instancia de servidor MCP con FastMCP()
  2. Se escribe una función de herramienta (convert_currency()) para realizar una acción; en este caso, recuperar información de divisas desde la Frankfurter API.
  3. Esta función se convierte en una herramienta MCP usando el decorador @mcp.tool().

Este ejercicio forma parte del curso

Introducción a Model Context Protocol (MCP)

Ver curso

Instrucciones del ejercicio

  • Revisa el código proporcionado para ver cómo una función se convierte en una herramienta para un servidor MCP.
  • En la línea 43, prueba la herramienta MCP con un importe y las divisas que elijas para convertir de y a.

Nota: tendrás que usar los códigos de divisa oficiales, como GBP para la libra esterlina británica.

ejercicio interactivo práctico

Prueba este ejercicio completando este código de ejemplo.

# 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)
Editar y ejecutar código