将数据库作为资源
现在把数据库信息作为资源提供给 MCP 服务器。这样下游就能用它来校验 LLM 请求的货币代码是否受支持,或者在用户界面中把货币代码做成下拉选择或自动补全。
数据库仍为 currencies.db,已为您提供用于实例化服务器的代码。
本练习是课程的一部分
Model Context Protocol (MCP) 入门
练习说明
- 建立到数据库(
currencies.db)的连接。 - 为该数据库连接创建一个新的 MCP 服务器资源。
- 执行数据库查询,使
get_currencies()函数返回数据库的内容。
交互式实操练习
通过完成这段示例代码来试试这个练习。
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Currency Converter")
# Connect to the database on startup
conn = sqlite3.____("____")
conn.row_factory = sqlite3.Row
# Create an MCP resource
@mcp.____("db://currencies")
def get_currencies() -> str:
"""
Get the list of currency names published by the European Central Bank for currency conversion.
Returns:
One line per currency (code - name), from the database.
"""
try:
# Query the database
cursor = conn.____("SELECT code, name FROM currencies")
rows = cursor.fetchall()
return "\n".join(f"{row['code']} - {row['name']}" for row in rows)
except sqlite3.Error as e: return f"Error: {e}"
result = get_currencies()
print(result[:200] + "..." if len(result) > 200 else result)