|
| 1 | +"""Prompt client example: list, inspect, and get prompts from a server. |
| 2 | +
|
| 3 | +cd to the `examples/snippets` directory and run: |
| 4 | + uv run prompt-client |
| 5 | +""" |
| 6 | + |
| 7 | +import asyncio |
| 8 | +import os |
| 9 | + |
| 10 | +from mcp import ClientSession, StdioServerParameters |
| 11 | +from mcp.client.stdio import stdio_client |
| 12 | +from mcp.types import TextContent |
| 13 | + |
| 14 | +server_params = StdioServerParameters( |
| 15 | + command="uv", |
| 16 | + args=["run", "server", "prompt_server", "stdio"], |
| 17 | + env={"UV_INDEX": os.environ.get("UV_INDEX", "")}, |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +async def run(): |
| 22 | + """Connect to the prompt server and exercise the prompts API.""" |
| 23 | + async with stdio_client(server_params) as (read, write): |
| 24 | + async with ClientSession(read, write) as session: |
| 25 | + await session.initialize() |
| 26 | + |
| 27 | + # 1. Discover which prompts the server exposes |
| 28 | + result = await session.list_prompts() |
| 29 | + print("Available prompts:") |
| 30 | + for prompt in result.prompts: |
| 31 | + args = ", ".join(f"{a.name}{'?' if not a.required else ''}" for a in (prompt.arguments or [])) |
| 32 | + print(f" - {prompt.name}({args}): {prompt.description}") |
| 33 | + |
| 34 | + # 2. Fetch the single-string prompt and print its message |
| 35 | + review = await session.get_prompt( |
| 36 | + "review_code", |
| 37 | + arguments={"code": "def add(a, b):\n return a + b"}, |
| 38 | + ) |
| 39 | + print("\nreview_code prompt messages:") |
| 40 | + for msg in review.messages: |
| 41 | + text = msg.content.text if isinstance(msg.content, TextContent) else str(msg.content) |
| 42 | + print(f" [{msg.role}] {text}") |
| 43 | + |
| 44 | + # 3. Fetch the multi-turn prompt and print each message in the thread |
| 45 | + debug = await session.get_prompt( |
| 46 | + "debug_error", |
| 47 | + arguments={"error": "NameError: name 'x' is not defined"}, |
| 48 | + ) |
| 49 | + print("\ndebug_error prompt messages:") |
| 50 | + for msg in debug.messages: |
| 51 | + text = msg.content.text if isinstance(msg.content, TextContent) else str(msg.content) |
| 52 | + print(f" [{msg.role}] {text}") |
| 53 | + |
| 54 | + |
| 55 | +def main(): |
| 56 | + """Entry point for the prompt client.""" |
| 57 | + asyncio.run(run()) |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + main() |
0 commit comments