開始使用免費開始

從 MCP 擷取資源與提示

你的貨幣伺服器提供一個資源(file://currencies.txt)與一個提示(convert_currency_prompt),會把使用者的請求與任務專屬的情境與規則結合。為了提供給 LLM,客戶端必須一次擷取這兩者。請實作一個名為 get_context_from_mcp() 的輔助函式,回傳資源文字與提示文字(已包含使用者查詢),好讓呼叫端能組出訊息。

currency_server.py 檔案已提供工具、資源與提示。請在同一個 session 中讀取資源,並用使用者輸入取得提示。

本練習屬於課程

Model Context Protocol(MCP)入門

檢視課程

練習說明

  • 在 session 內,呼叫方法讀取位於 "file://currencies.txt" 的資源。
  • 呼叫方法透過名稱與使用者輸入取得提示:使用提示名稱 "convert_currency_prompt",以及一個 arguments 字典,鍵為 "currency_request"、值為 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?")))
編輯並執行程式碼