始める無料で始める

クライアントからプロンプトを取得する

次に、ユーザーの入力を使って通貨サーバーから特定のプロンプトを取得しましょう。テンプレートとユーザーのリクエストが組み合わさり、LLM が変換ツールを呼び出すかどうかを判断する前に渡すプロンプトが生成されます。

この演習はコースの一部です

Model Context Protocol(MCP)入門

コースを見る

演習の手順

  • セッションを初期化した後、プロンプト名と、ユーザーの入力を含む arguments ディクショナリを渡して、名前でプロンプトを取得するメソッドを呼び出します。
  • プロンプト結果の最初のメッセージのテキスト内容を取り出して表示します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def read_prompt(user_input: str = "How much is 50 GBP in euros?", prompt_name: str = "convert_currency_prompt") -> str:
    """Retrieve a prompt from the MCP server with user input."""
    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()

            # Retrieve the prompt with the user's input
            prompt = await session.____(prompt_name, arguments={"currency_request": user_input})

            # Print the full prompt text (template + user request)
            text = prompt.____[0].____.____
            print(text)
            return text

asyncio.run(read_prompt(user_input="How much is 50 GBP in euros?"))
コードを編集して実行