API 인증이 필요한 경우
외부 API에 API 키가 필요한 경우, 키는 서버의 환경 변수에 저장하고 외부 요청 헤더에만 첨부해야 합니다. 클라이언트는 키를 주고받지 않습니다. 이번 연습 문제에서는 통화 서버의 convert_currency 도구에 선택적 API 키 지원을 추가해 보겠습니다.
Frankfurter API는 기본 사용 시 키가 필요하지 않지만, 많은 API는 키를 요구합니다. 환경 변수(예: CURRENCY_API_KEY)에서 선택적 키를 읽어, 설정된 경우 Authorization: Bearer 헤더로 요청에 추가합니다.
MCP 서버는 이미 인스턴스화되어 mcp 변수에 저장되어 있습니다. os 모듈도 이미 임포트되어 있습니다.
이 연습은 강의의 일부입니다
Model Context Protocol (MCP) 입문
연습 안내
- 환경 변수에서
"CURRENCY_API_KEY"API 키를 읽어와,"Bearer "와 키를 합친 값을"Authorization"헤더에 추가하세요. - 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"))