जब APIs को ऑथेंटिकेशन चाहिए
जब कोई external API एक API key मांगती है, तो वह key केवल server के environment में रहनी चाहिए और उसे सिर्फ outbound request header में जोड़ा जाना चाहिए। क्लाइंट कभी भी इस key को न भेजता है, न प्राप्त करता है। इस अभ्यास में आप currency सर्वर के convert_currency टूल में वैकल्पिक API key सपोर्ट जोड़ेंगे।
Frankfurter API को basic उपयोग के लिए key की ज़रूरत नहीं होती, लेकिन कई APIs को होती है। आप environment से एक वैकल्पिक key पढ़ेंगे (जैसे CURRENCY_API_KEY) और, अगर सेट हो, तो उसे request में Authorization: Bearer हेडर के रूप में जोड़ेंगे।
एक MCP सर्वर पहले से instantiate किया जा चुका है और mcp वैरिएबल में स्टोर है। os मॉड्यूल आपके लिए पहले से import किया गया है।
यह अभ्यास पाठ्यक्रम का हिस्सा है
Model Context Protocol (MCP) परिचय
अभ्यास निर्देश
- environment variables से
"CURRENCY_API_KEY"API key पढ़ें और उसे request के"Authorization"हेडर में"Bearer "प्लस key की वैल्यू के साथ जोड़ें। - API के GET request में 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"))