當 API 需要驗證時
當外部 API 需要 API 金鑰時,金鑰應該放在伺服器的環境中,並且只在對外送出的請求標頭中附加。用戶端不會送出或接收這個金鑰。這個練習中,你將為 currency 伺服器的 convert_currency 工具加入可選的 API 金鑰支援。
Frankfurter API 在基本使用時不需要金鑰,但許多 API 會需要。你將從環境(例如 CURRENCY_API_KEY)讀取可選的金鑰,並在有設定時,將它以 Authorization: Bearer 標頭加入請求中。
一個 MCP 伺服器已經建立並存為變數 mcp。os 模組也已經為你匯入。
本練習屬於課程
Model Context Protocol(MCP)入門
練習說明
- 從環境變數讀取
"CURRENCY_API_KEY"API 金鑰,並在請求中將它加入到"Authorization"標頭,值為"Bearer "加上該金鑰。 - 在 API 的 GET 請求中傳入這個 headers。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
@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"))