Bắt đầu ngayBắt đầu miễn phí

Liệt kê tài nguyên từ Client

Máy chủ của bạn đã được viết trong tệp currency_server.py và sẵn sàng để kết nối! Trước hết, hãy tạo một client có thể liệt kê các tài nguyên có sẵn trên máy chủ này.

Bài tập này là một phần của khóa học

Giới thiệu về Model Context Protocol (MCP)

Xem khóa học

Hướng dẫn bài tập

  • Bên trong ngữ cảnh phiên máy chủ, truy xuất các tài nguyên hiện có.
  • Lặp qua response.resources và in URI, tên và mô tả của từng tài nguyên bằng cách sử dụng các thuộc tính tương ứng.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

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())
Chỉnh sửa và Chạy Mã