Your First MCP Server
Time to get hands-on with your first MCP server! We've provided all the code for you here, which we'll teach in the next video, but take a look at the flow of the code:
- An MCP server instance is defined with
FastMCP() - A tool function (
convert_currency()) is written to perform some action; in this case, retrieving currency information from the Frankfurter API. - This function is converted into an MCP tool using the
@mcp.tool()decorator.
This exercise is part of the course
Introduction to Model Context Protocol (MCP)
Exercise instructions
- Take a look at the code provided to see how a function is converted into a tool for an MCP server.
- On line 43, test the MCP tool with an amount and your choice of currencies to convert to and from.
Note: You'll need to use the official currency codes, like GBP for the British pound sterling.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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)