Aan de slagGa gratis aan de slag

Retrieving a Prompt from the Client

Now retrieve a specific prompt from the currency server with user input so the template and the user's request are combined. This is what you would pass to an LLM before it decides whether to call the conversion tool.

Deze oefening maakt deel uit van de cursus

Introduction to Model Context Protocol (MCP)

Cursus bekijken

Oefeninstructies

  • After initializing the session, call the method to get a prompt by name, passing the prompt name and an arguments dict with the user's input.
  • Extract and print the text content of the first message in the prompt result.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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?"))
Code bewerken en uitvoeren