ComenzarEmpieza gratis

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.

Este ejercicio forma parte del curso

Introduction to Model Context Protocol (MCP)

Ver curso

Instrucciones del ejercicio

  • 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.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

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?"))
Editar y ejecutar código