Lấy Resource và Prompt từ MCP
Máy chủ tiền tệ của bạn cung cấp một resource (file://currencies.txt) và một prompt (convert_currency_prompt) kết hợp yêu cầu của người dùng với ngữ cảnh và quy tắc dành riêng cho tác vụ. Để đưa vào LLM, client cần lấy cả hai trong một lần. Hãy triển khai hàm tiện ích get_context_from_mcp() trả về phần văn bản của resource và văn bản của prompt (đã có sẵn truy vấn của người dùng) để bên gọi có thể xây dựng thông điệp.
Tệp currency_server.py có sẵn một tool, resource và prompt. Dùng cùng một session để đọc resource và lấy prompt với đầu vào của người 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
- Bên trong session, gọi phương thức để đọc resource tại
"file://currencies.txt". - Gọi phương thức để lấy prompt theo tên với đầu vào của người dùng: dùng tên prompt
"convert_currency_prompt"và một dictargumentsvới khóa"currency_request"và giá trịuser_query.
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 get_context_from_mcp(user_query: str) -> tuple[str, str]:
"""Fetch resource content and prompt text 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()
# Read the resource (supported currencies)
resource_result = await session.____("file://currencies.txt")
resource_text = resource_result.contents[0].text
# Get the prompt with the user's query
prompt_result = await session.____("convert_currency_prompt",
arguments={"currency_request": user_query})
prompt_text = prompt_result.messages[0].content.text
return resource_text, prompt_text
print(asyncio.run(get_context_from_mcp("How much is 50 GBP in euros?")))