ดึง Resource และ Prompt จาก MCP
เซิร์ฟเวอร์สกุลเงินของคุณเปิดเผย resource (file://currencies.txt) และ prompt (convert_currency_prompt) ที่รวมคำขอของผู้ใช้เข้ากับบริบทและกฎเฉพาะสำหรับงาน เพื่อส่งข้อมูลให้ LLM client จะต้องดึงทั้งสองอย่างในครั้งเดียว ให้สร้างฟังก์ชันช่วยชื่อ get_context_from_mcp() ที่คืนค่าทั้งข้อความจาก resource และข้อความ prompt (ซึ่งมีคำถามของผู้ใช้ฝังอยู่แล้ว) เพื่อให้ผู้เรียกสามารถสร้างข้อความได้
ไฟล์ currency_server.py มีให้พร้อมกับ tool, resource, และ prompt ให้ใช้ session เดียวกันในการอ่าน resource และดึง prompt พร้อมกับ input ของผู้ใช้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Model Context Protocol (MCP) เบื้องต้น
คำแนะนำการฝึกหัด
- ภายใน session ให้เรียกเมธอดเพื่ออ่าน resource ที่
"file://currencies.txt" - เรียกเมธอดเพื่อดึง prompt ตามชื่อพร้อม input ของผู้ใช้ โดยใช้ชื่อ prompt ว่า
"convert_currency_prompt"และ dict ของargumentsที่มี key เป็น"currency_request"และ value เป็นuser_query
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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?")))