开始使用免费开始使用

添加文档字符串与类型注解

现在为您的 convert_currency() 工具添加 文档字符串(docstring)类型注解(type hints),以便 LLM 更容易使用它。如果没有这些,LLM 可能无法有效选择要调用的工具,或会向参数传递错误的值——都会导致应用表现不稳定!

一个 MCP 服务器已使用 FastMCP 实例化并赋值给 mcp

本练习是课程的一部分

Model Context Protocol (MCP) 入门

查看课程

练习说明

  • 为函数参数与返回对象添加合适的类型。
  • 补全文档字符串,使三个函数参数与其定义一一对应。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Adding typing to the function arguments and return object
@mcp.tool()
def convert_currency(amount: ____, from_currency: ____, to_currency: ____) -> ____:
    # Complete the docstring with the function arguments
    """
    Convert an amount from one currency to another using current exchange rates.

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

    Returns:
        A string with the conversion result and exchange rate
    """

    url = f"https://api.frankfurter.dev/v1/latest?base={from_currency}&symbols={to_currency}"

    response = requests.get(url)
    data = response.json()
    rate = data['rates'].get(to_currency)

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

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

print(convert_currency(amount=100, from_currency="EUR", to_currency="USD"))
编辑并运行代码