开始使用免费开始使用

参数化的数据库查找工具

按需查找工具可让 LLM 按名称或代码搜索货币,而无需加载完整列表。请使用参数化查询(占位符 ?)来避免提示注入,并设置行数上限,使返回结果保持可控。

本练习是课程的一部分

Model Context Protocol (MCP) 入门

查看课程

练习说明

  • 定义名为 lookup_currencies() 的工具,在 currencies 中查找 namecode 包含 prefix 的行(不区分大小写)。
  • 使用参数化 SQL 查询将 prefix 填入 ? 占位符;使用 LIMIT 50 限制返回的行数。

交互式实操练习

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

# Add lookup_currencies(prefix): find rows where name or code contains prefix
@mcp.____()
def ____(____: str) -> str:
    """Find currencies whose code or name contains the given prefix."""
    try:
        # Use parameterized query and LIMIT 50
        cursor = conn.execute(
            "SELECT code, name FROM currencies WHERE name LIKE ? OR code LIKE ? LIMIT ____",
            (f"%{____}%", f"%{____}%")
        )
        rows = cursor.fetchall()
        return "\n".join(f"{row['code']} - {row['name']}" for row in rows)
    except sqlite3.Error as e:
        return f"Database error: {e}"

print(lookup_currencies("Euro"))
编辑并运行代码