शुरू करेंमुफ़्त में शुरू करें

आपका पहला MCP सर्वर

अब आपके पहले MCP सर्वर के साथ हाथों-हाथ काम करने का समय! हमने यहाँ आपके लिए सारा कोड पहले से दे दिया है, जिसका विवरण हम अगले वीडियो में समझाएँगे। फिलहाल, कोड के फ्लो पर नज़र डालिए:

  1. FastMCP() के साथ एक MCP सर्वर इंस्टेंस परिभाषित किया गया है।
  2. एक टूल फंक्शन (convert_currency()) लिखा गया है जो कोई एक्शन करता है; इस केस में, Frankfurter API से करेंसी जानकारी लाता है।
  3. इस फंक्शन को @mcp.tool() डेकोरेटर का उपयोग करके MCP टूल में बदला गया है.

यह अभ्यास पाठ्यक्रम का हिस्सा है

Model Context Protocol (MCP) परिचय

पाठ्यक्रम देखें

अभ्यास निर्देश

  • दिए गए कोड को देखें कि किस तरह एक फंक्शन को MCP सर्वर के लिए टूल में बदला जाता है.
  • लाइन 43 पर, किसी अमाउंट और अपनी पसंद की करेंसी चुनकर, किसमें कन्वर्ट करना है और किससे करना है — इन वैल्यू के साथ MCP टूल को टेस्ट करें.

नोट: आपको आधिकारिक करेंसी कोड इस्तेमाल करने होंगे, जैसे ब्रिटिश पाउंड स्टर्लिंग के लिए 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)
कोड संपादित करें और चलाएँ