您的第一个 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)