เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

เมื่อ API ต้องการการยืนยันตัวตน

เมื่อ API ภายนอกต้องใช้ API key นั้น key ควรเก็บไว้ในสภาพแวดล้อมของเซิร์ฟเวอร์ และแนบไปกับ request header ขาออกเท่านั้น ฝั่ง client จะไม่ส่งหรือรับ key โดยตรง ในแบบฝึกหัดนี้ จะเพิ่มการรองรับ API key แบบ optional ให้กับ tool convert_currency ของ currency server

Frankfurter API ไม่จำเป็นต้องใช้ key สำหรับการใช้งานพื้นฐาน แต่ API หลายตัวต้องการ จะอ่าน key แบบ optional จาก environment (เช่น CURRENCY_API_KEY) และหากมีการกำหนดค่าไว้ ให้เพิ่ม key นั้นใน request เป็น Authorization: Bearer header

MCP server ได้รับการสร้างและเก็บไว้ในตัวแปร mcp แล้ว และได้ import โมดูล os ให้แล้วเช่นกัน

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Model Context Protocol (MCP) เบื้องต้น

ดูคอร์ส

คำแนะนำการฝึกหัด

  • อ่าน API key "CURRENCY_API_KEY" จาก environment variables แล้วเพิ่มลงใน "Authorization" header โดยกำหนดค่าเป็น "Bearer " ตามด้วย key ที่อ่านได้
  • ส่ง headers ไปพร้อมกับ API GET request

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

@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"))
แก้ไขและรันโค้ด