Liệt kê Prompts từ Client
Máy chủ tiền tệ của bạn đã được viết trong currency_server.py với một tool, một resource và một prompt. Hãy tạo một client để liệt kê các prompt có sẵn trên máy chủ này, giúp bạn khám phá các mẫu prompt mà LLM có thể sử dụng.
Bài tập này là một phần của khóa học
Giới thiệu về Model Context Protocol (MCP)
Hướng dẫn bài tập
- Kết nối tới máy chủ MCP, khởi tạo session, và gọi phương thức liệt kê các prompt hiện có, gán kết quả vào một biến.
- In tên của từng prompt (tên hàm từ phía máy chủ, không phải tiêu đề).
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def list_prompts():
"""List all available prompts from the MCP server."""
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()
# List available prompts
prompts = await session.____()
print(f"Available prompts: {[p.____ for p in prompts.prompts]}")
return prompts.prompts
asyncio.run(list_prompts())