当 API 需要认证时
当外部 API 需要 API key 时,key 应该保存在服务器的环境中,并且只在向外发送的请求头中附加。客户端永远不发送或接收该 key。此练习中,您将为货币服务器的 convert_currency 工具添加可选的 API key 支持。
Frankfurter API 在基础用法下不需要 key,但许多 API 需要。您将从环境中读取一个可选的 key(例如 CURRENCY_API_KEY),如果已设置,则将其作为 Authorization: Bearer 请求头加入请求。
一个 MCP 服务器已经实例化并存储在变量 mcp 中。os 模块也已为您导入。
本练习是课程的一部分
Model Context Protocol (MCP) 入门
练习说明
- 从环境变量中读取
"CURRENCY_API_KEY"API key,并将其作为"Authorization"请求头加入,值为"Bearer "加上该 key。 - 在 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"))