Getting Prompts
00:00
You’re now ready to start getting prompts from your MCP servers. And to do that, you’re going to create the subcommand get that accepts a prompt name, a server to get that prompt from, and then displays the prompt to the user.
00:15
To implement this subcommand, open the file cli.py. At the top, you can use the decorator mcp_cli.command to create a new command.
00:25
This one will be get, so its help text could be something like "Get a prompt from its name."
00:34 And this accepts two arguments this time. You’re going to need the command for the server that contains the prompt, and you’re going to need to know the name of the prompt,
00:47
And these get passed to the function get, which accepts an argument server_command and a prompt, both strings. It returns None, and you’ve seen this pattern already.
01:00
It defers to using asyncio to run the coroutine that actually does the job of getting the prompt from the server. How do you define your coroutine?
01:14
async def _get accepts the server command as a string, the prompt name as a string. This should really be prompt_name.
01:23
You can use Command-D or Control-D to select the same string multiple times in most IDEs. This returns None. And now you instantiate your MCP client and use it as an asynchronous context manager as you’ve done in the previous lessons.
01:41
You pass in the server command, and this is your client. And now you can get the prompt by accessing the client_session in your client and running the function get_prompt that accepts the prompt name as an argument.
01:59
Now this is not a regular function, it’s a coroutine, so it must be awaited, and the result can be saved in the variable prompt. Now this prompt result has a very specific format. You can check the documentation to see exactly what it is. You will likely want to iterate over its attribute messages, and you will want to print each message.
02:24
Make sure you save the file cli.py, open your terminal, and now you can test this by writing uv run mcp-client get mcp-data, and then in quotes, the quotes are very important, "Sales analysis", because the quotes say that these two words, sales and analysis, make up the prompt name.
02:47
Press Enter, give it a second, and you should see a bit of output that starts with role='user', content=TextContent, and eventually you should be able to find the text that says, "Determine the total number of sales" etc., etc.
03:03 So this allows you to get a prompt by name from any MCP server you connect to. In the next lesson, you’re going to learn how to fetch resources from MCP servers.
Become a Member to join the conversation.
