从客户端列出资源
您的服务器已写入文件 currency_server.py,现在可以连接了!首先,请创建一个客户端,用于列出该服务器上可用的资源。
本练习是课程的一部分
Model Context Protocol (MCP) 入门
练习说明
- 在服务器会话上下文中,获取可用的资源。
- 遍历
response.resources,使用其属性打印每个资源的 URI、名称和描述。
交互式实操练习
通过完成这段示例代码来试试这个练习。
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def list_resources():
"""List all available resources from the MCP server."""
params = StdioServerParameters(command=sys.executable, args=["currency_server.py"])
async with stdio_client(params) as (reader, writer):
async with ClientSession(reader, writer) as session:
await session.initialize()
# Get the list of resources
response = ____ ____()
print("Available resources:")
# Print each resource's URI, name, and description
for resource in response.____:
print(f" - {resource.____}")
print(f" Name: {resource.____}")
print(f" Description: {resource.____}")
return response.resources
asyncio.run(list_resources())