開始使用免費開始

你的第一個 MCP 伺服器

是時候動手做你的第一個 MCP 伺服器了!我們已經把所有程式碼都準備好,接下來的影片會逐步講解。不過你先看看程式碼的流程:

  1. 使用 FastMCP() 定義一個 MCP 伺服器實例。
  2. 撰寫工具函式(convert_currency())來執行特定動作;本例是從 Frankfurter API 取得匯率資訊。
  3. 使用 @mcp.tool() 裝飾器,將這個函式轉換成 MCP 工具。

本練習屬於課程

Model Context Protocol(MCP)入門

檢視課程

練習說明

  • 先看看提供的程式碼,了解如何把函式轉換成 MCP 伺服器可用的工具。
  • 在第 43 行,使用金額與你選擇的幣別,測試這個 MCP 工具的「轉入」與「轉出」。

注意:你需要使用官方幣別代碼,例如英鎊用 GBP

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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)
編輯並執行程式碼