开始使用免费开始使用

从 MCP 获取资源与提示

您的货币服务器提供了一个资源(file://currencies.txt)和一个提示(convert_currency_prompt),用于把用户请求与任务相关的上下文和规则组合起来。为了给 LLM 提供输入,客户端需要一次性获取两者。请实现一个名为 get_context_from_mcp() 的辅助函数,返回资源文本和提示文本(其中已包含用户的查询),以便调用方构建消息。

currency_server.py 文件已提供工具、资源和提示。请在同一个会话中读取资源,并使用用户输入获取提示。

本练习是课程的一部分

Model Context Protocol (MCP) 入门

查看课程

练习说明

  • 在会话中,调用方法读取 "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?")))
编辑并运行代码