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

MCP Server ตัวแรกของคุณ

ถึงเวลาลงมือสร้าง MCP server ตัวแรกกันแล้ว! เราเตรียมโค้ดทั้งหมดไว้ให้แล้ว และจะอธิบายรายละเอียดในวิดีโอถัดไป แต่ลองดูขั้นตอนการทำงานของโค้ดนี้ก่อน:

  1. กำหนด MCP server instance ด้วย FastMCP()
  2. เขียนฟังก์ชัน tool (convert_currency()) เพื่อดำเนินการบางอย่าง ในที่นี้คือดึงข้อมูลอัตราแลกเปลี่ยนจาก Frankfurter API
  3. แปลงฟังก์ชันนี้ให้เป็น MCP tool โดยใช้ decorator @mcp.tool()

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

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

ดูคอร์ส

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

  • ดูโค้ดที่เตรียมไว้เพื่อทำความเข้าใจว่าฟังก์ชันถูกแปลงเป็น tool สำหรับ MCP server ได้อย่างไร
  • ในบรรทัดที่ 43 ทดสอบ MCP tool โดยระบุจำนวนเงินและสกุลเงินที่ต้องการแปลงตามต้องการ

หมายเหตุ: ต้องใช้รหัสสกุลเงินมาตรฐาน เช่น GBP สำหรับปอนด์สเตอร์ลิงของอังกฤษ

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

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

# Create an MCP server instance
mcp = FastMCP("Currency Converter")

@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.

    Args:
        amount: The amount to convert
        from_currency: Source currency code (e.g., 'USD', 'EUR', 'GBP')
        to_currency: Target currency code (e.g., 'USD', 'EUR', 'GBP')

    Returns:
        A string with the conversion result and exchange rate
    """
    # API endpoint for Frankfurter
    url = f"https://api.frankfurter.dev/v1/latest?base={from_currency}&symbols={to_currency}"

    try:
        # Make the API request
        response = requests.get(url)
        response.raise_for_status()

        # Parse the response
        data = response.json()

        # Get the exchange rate
        rate = data['rates'].get(to_currency)

        if rate is None:
            return f"Could not find exchange rate for {from_currency} to {to_currency}"

        # Calculate the converted amount
        converted_amount = amount * rate

        return f"{amount} {from_currency} = {converted_amount:.2f} {to_currency} (Rate: {rate})"

    except requests.exceptions.RequestException as e:
        return f"Error converting currency: {str(e)}"

print("Testing Currency Converter:")
result = convert_currency(amount=100, from_currency="USD", to_currency="EUR")
print(result)
แก้ไขและรันโค้ด