client_raw.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import asyncio
  2. import logging
  3. from langchain_mcp_adapters.tools import load_mcp_tools
  4. from mcp import ClientSession
  5. from mcp.client.streamable_http import streamablehttp_client
  6. # 定义服务器地址
  7. server_url = "http://127.0.0.1:8001/mcp"
  8. # 定义mcp客户端
  9. mcp_client = None
  10. # 配置日志
  11. logging.basicConfig(
  12. level=logging.DEBUG, # 提高日志级别以捕获更多信息
  13. format='[客户端] %(asctime)s - %(levelname)s - %(message)s'
  14. )
  15. async def main():
  16. global mcp_client
  17. logging.info(f"准备连接到 Streamable-HTTP 服务器: {server_url}")
  18. try:
  19. # 启动 MCP server,通过streamable建立连接
  20. async with streamablehttp_client(server_url) as (read, write, _):
  21. logging.info("连接已成功建立!")
  22. # 使用读写通道创建 MCP 会话
  23. async with ClientSession(read, write) as session:
  24. try:
  25. await session.initialize()
  26. logging.info("会话初始化成功,可以开始调用工具。")
  27. # 动态创建一个临时类 MCPClientHolder,把 session 放进去。这样就可以在函数外部通过 mcp_client.session 调用 MCP 工具
  28. mcp_client = type("MCPClientHolder", (), {"session": session})()
  29. # 从 session 自动获取 MCP server 提供的工具列表。
  30. tools = await load_mcp_tools(session)
  31. # print(f"tools-->{tools}")
  32. # 调用远程工具
  33. logging.info("--> 正在调用工具: query_high_frequency_question")
  34. response = await session.call_tool("query_high_frequency_question", {})
  35. print(f"response-->{response}")
  36. logging.info(f"<-- 收到响应: {response}")
  37. print("-" * 30)
  38. logging.info("--> 正在调用工具: get_weather")
  39. response = await session.call_tool("get_weather", {})
  40. print(f"response-->{response}")
  41. logging.info(f"<-- 收到响应: {response}")
  42. except Exception as e:
  43. logging.error(f"调用工具时发生错误: {e}", exc_info=True)
  44. raise
  45. except Exception as e:
  46. logging.error(f"连接或会话初始化时发生错误: {e}", exc_info=True)
  47. logging.error("请确认服务端脚本已启动并运行在 http://127.0.0.1:8001/mcp")
  48. raise
  49. if __name__ == "__main__":
  50. try:
  51. asyncio.run(main())
  52. except Exception as e:
  53. logging.error(f"客户端运行失败: {e}", exc_info=True)