始める無料で始める

はじめての 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)
コードを編集して実行