定义 MCP 服务器资源
您正在扩展用于货币转换的 MCP 服务器,使其能够访问所用 API 支持的货币列表。European Central Bank 会发布一个名为 currencies.txt 的货币代码列表文件,该文件已放在您的服务器目录中。客户端可以利用它来确保 LLM 向工具函数传递的参数值是正确的。
您的任务是定义一个名为 get_currencies() 的 MCP 资源,用于读取 currencies.txt 的内容。
本练习是课程的一部分
Model Context Protocol (MCP) 入门
练习说明
- 使用正确的装饰器与
"file://currencies.txt"URI,将get_currencies()函数转换为一个资源。 - 完成
get_currencies()函数,以打开并读取currencies.txt文件的内容。 - 打印调用
get_currencies()的结果,以验证该资源是否正常工作。
交互式实操练习
通过完成这段示例代码来试试这个练习。
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Currency Converter")
# Define a resource for the currencies file
____
def get_currencies() -> str:
"""
Get the list of currency names published by the European Central Bank for currency conversion.
Returns:
Contents of the currencies.txt file with currency names
"""
# Open currencies.txt and read the data
try:
with open('____', 'r') as f:
content = f.____
return content
except FileNotFoundError:
return "currencies.txt file not found"
# Test the resource function
print(____)