05_UseMCPToolInAgent.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from hello_agents import SimpleAgent, HelloAgentsLLM
  2. from hello_agents.tools import MCPTool
  3. print("=" * 70)
  4. print("方式1:使用内置演示服务器")
  5. print("=" * 70)
  6. agent = SimpleAgent(name="助手", llm=HelloAgentsLLM())
  7. # 无需任何配置,自动使用内置演示服务器
  8. # 内置服务器提供:add, subtract, multiply, divide, greet, get_system_info
  9. mcp_tool = MCPTool() # 默认name="mcp"
  10. agent.add_tool(mcp_tool)
  11. # 智能体可以使用内置工具
  12. response = agent.run("计算 123 + 456")
  13. print(response) # 智能体会自动调用add工具
  14. print("\n" + "=" * 70)
  15. print("方式2:连接外部MCP服务器(使用多个服务器)")
  16. print("=" * 70)
  17. # 重要:为每个MCP服务器指定不同的name,避免工具名称冲突
  18. # 示例1:连接到社区提供的文件系统服务器
  19. fs_tool = MCPTool(
  20. name="filesystem", # 指定唯一名称
  21. description="访问本地文件系统",
  22. server_command=["npx", "-y", "@modelcontextprotocol/server-filesystem", "."]
  23. )
  24. agent.add_tool(fs_tool)
  25. # 示例2:连接到自定义的 Python MCP 服务器
  26. # 关于如何编写自定义MCP服务器,请参考10.5章节
  27. custom_tool = MCPTool(
  28. name="custom_server", # 使用不同的名称
  29. description="自定义业务逻辑服务器",
  30. server_command=["python", "my_mcp_server.py"]
  31. )
  32. agent.add_tool(custom_tool)
  33. print("\n当前Agent拥有的工具:")
  34. print(f"- {mcp_tool.name}: {mcp_tool.description}")
  35. print(f"- {fs_tool.name}: {fs_tool.description}")
  36. print(f"- {custom_tool.name}: {custom_tool.description}")
  37. # Agent现在可以自动使用这些工具!
  38. response = agent.run("请读取my_README.md文件,并总结其中的主要内容")
  39. print(response)