开始使用免费开始使用

调用服务器工具

现在,您将从客户端触发服务器中的工具调用!同样,您将使用异步操作,确保在等待其他操作完成时,程序不会中断或卡死。

本练习是课程的一部分

Model Context Protocol (MCP) 入门

查看课程

练习说明

  • 使用用户提供的 tool_namearguments 参数调用工具;并使用合适的 Python 关键字让调用暂停,等待服务器响应。
  • 提取并打印服务器响应中的文本内容。
  • 使用一组有效参数运行 "convert_currency" 工具(这里可任选数值与货币)。

交互式实操练习

通过完成这段示例代码来试试这个练习。

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def call_mcp_tool(tool_name: str, arguments: dict) -> str:
    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()

            # Call the currency conversion tool
            result = ____ ____(tool_name, arguments)

            # Extract and print the text content of the server response
            text_content = result.____[0].____

            print(f"Conversion Result: {text_content}")
            return text_content

# Run the "convert_currency" tool
asyncio.run(
    call_mcp_tool("convert_currency",
                  {"amount": 250.0, "from_currency": "USD", "to_currency": "EUR"})
)
编辑并运行代码