step3_call_multiple_tools.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """
  2. 第 3 步测试:一个 MCP Server 暴露多个工具,并分别调用它们。
  3. 运行:
  4. python step3_call_multiple_tools.py
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. import sys
  9. from pathlib import Path
  10. from langchain_mcp_adapters.client import MultiServerMCPClient
  11. async def main() -> None:
  12. server_file = Path(__file__).with_name("my_mcp_demo.py").resolve()
  13. client = MultiServerMCPClient(
  14. {
  15. "travel-tools": {
  16. "transport": "stdio",
  17. "command": sys.executable,
  18. "args": [str(server_file)],
  19. }
  20. }
  21. )
  22. tools = await client.get_tools()
  23. tool_map = {tool.name: tool for tool in tools}
  24. print("MCP Client 发现了这些工具:")
  25. for tool_name in tool_map:
  26. print(f"- {tool_name}")
  27. hotel_result = await tool_map["search_hotels"].ainvoke(
  28. {
  29. "city": "重庆",
  30. "nights": 2,
  31. "budget_per_night": 400,
  32. }
  33. )
  34. transport_result = await tool_map["search_transport"].ainvoke(
  35. {
  36. "origin": "成都",
  37. "destination": "重庆",
  38. "travel_date": "2026-08-15",
  39. }
  40. )
  41. print("\n住宿工具返回:")
  42. print(hotel_result)
  43. print("\n交通工具返回:")
  44. print(transport_result)
  45. if __name__ == "__main__":
  46. asyncio.run(main())