Quando le API richiedono l'autenticazione
Quando un'API esterna richiede una chiave API, la chiave deve risiedere nell'ambiente del server ed essere aggiunta solo nell'header della richiesta in uscita. Il client non invia né riceve mai la chiave. In questo esercizio aggiungerai il supporto opzionale per la chiave API allo strumento convert_currency del server di cambio valute.
La Frankfurter API non richiede una chiave per l'uso di base, ma molte API lo fanno. Leggerai una chiave opzionale dall'ambiente (ad es. CURRENCY_API_KEY) e, se presente, la aggiungerai alla richiesta come header Authorization: Bearer.
Un server MCP è già stato istanziato e memorizzato nella variabile mcp. Il modulo os è già stato importato per te.
Questo esercizio fa parte del corso
Introduzione al Model Context Protocol (MCP)
Istruzioni dell'esercizio
- Leggi la chiave API
"CURRENCY_API_KEY"dalle variabili d'ambiente e aggiungila all'header"Authorization"con il valore"Bearer "più la chiave nella richiesta. - Passa gli header nella richiesta API GET.
esercizio interattivo pratico
Prova questo esercizio completando questo codice di esempio.
@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"))