나의 첫 번째 MCP 서버
첫 번째 MCP 서버를 직접 체험해 볼 시간입니다! 코드는 모두 미리 준비되어 있으며, 다음 영상에서 자세히 배울 예정입니다. 지금은 코드의 전체 흐름을 살펴보세요.
FastMCP()로 MCP 서버 인스턴스를 정의합니다.- 특정 작업을 수행하는 툴 함수(
convert_currency())를 작성합니다. 여기서는 Frankfurter API에서 환율 정보를 가져옵니다. @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)