始める無料で始める

APIの認証が必要な場合

外部APIがAPIキーを必要とする場合、そのキーはサーバーの環境変数に保存し、送信リクエストのヘッダーにのみ付与するのが基本です。クライアントがキーを送受信することはありません。この演習では、通貨サーバーの convert_currency ツールに、オプションのAPIキー対応を追加しましょう。

Frankfurter API は基本的な利用においてキーを必要としませんが、多くのAPIでは必要です。環境変数(例:CURRENCY_API_KEY)からオプションのキーを読み取り、設定されている場合は Authorization: Bearer ヘッダーとしてリクエストに付与します。

MCPサーバーはすでに変数 mcp としてインスタンス化されています。また、os モジュールはすでにインポート済みです。

この演習はコースの一部です

Model Context Protocol(MCP)入門

コースを見る

演習の手順

  • 環境変数から "CURRENCY_API_KEY" を読み取り、"Authorization" ヘッダーに "Bearer " とキーを連結した値を設定してください。
  • APIのGETリクエストにそのヘッダーを渡してください。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

@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."""
    url = f"https://api.frankfurter.dev/v1/latest?base={from_currency}&symbols={to_currency}"
    # Read optional API key from the server's environment
    headers = {}
    api_key = os.environ.get(____)
    if api_key:
        headers["Authorization"] = f"Bearer {____}"
    try:
        # Pass headers (and timeout) to the request; key never goes in the URL
        r = requests.get(url, ____=____, timeout=10)
        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})"
    except requests.exceptions.RequestException as e:
        return f"Error converting currency: {e}"

print(convert_currency(10, "USD", "EUR"))
コードを編集して実行