client_raw.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. import asyncio
  2. from mcp import ClientSession
  3. from mcp.client.sse import sse_client
  4. from langchain_mcp_adapters.tools import load_mcp_tools
  5. # MCP server URL for SSE connection
  6. server_url = "http://localhost:8001/sse"
  7. # 定义mcp客户端
  8. mcp_client = None
  9. # 主要的异步函数run_agent
  10. async def run():
  11. global mcp_client
  12. # 启动 MCP server,通过 SSE 建立异步连接。
  13. async with sse_client(url=server_url) as streams:
  14. # 使用读写通道创建 MCP 会话
  15. async with ClientSession(*streams) as session:
  16. await session.initialize()
  17. # 动态创建一个临时类 MCPClientHolder,把 session 放进去。这样就可以在函数外部通过 mcp_client.session 调用 MCP 工具
  18. mcp_client = type("MCPClientHolder", (), {"session": session})()
  19. # 从 session 自动获取 MCP server 提供的工具列表。
  20. tools = await load_mcp_tools(session)
  21. # print(f"tools-->{tools}")
  22. # 调用 MCP server 的 get_weather 工具
  23. response=await session.call_tool("get_weather", arguments={})
  24. print(f"response-->{response}")
  25. # 启动运行agent
  26. if __name__ == "__main__":
  27. asyncio.run(run())