始める無料で始める

クライアントからリソースを一覧表示する

サーバーのコードは 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())
コードを編集して実行