04_MCPTransport.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. from hello_agents.tools import MCPTool
  2. # 1. Memory Transport - 内存传输(用于测试)
  3. # 不指定任何参数,使用内置演示服务器
  4. mcp_tool = MCPTool()
  5. # 2. Stdio Transport - 标准输入输出传输(本地开发)
  6. # 使用命令列表启动本地服务器
  7. mcp_tool = MCPTool(server_command=["python", "examples/mcp_example_server.py"])
  8. # 3. Stdio Transport with Args - 带参数的命令传输
  9. # 可以传递额外参数
  10. mcp_tool = MCPTool(server_command=["python", "examples/mcp_example_server.py", "--debug"])
  11. # 4. Stdio Transport - 社区服务器(npx方式)
  12. # 使用npx启动社区MCP服务器
  13. mcp_tool = MCPTool(server_command=["npx", "-y", "@modelcontextprotocol/server-filesystem", "."])
  14. # 5. HTTP/SSE/StreamableHTTP Transport
  15. # 注意:MCPTool主要用于Stdio和Memory传输
  16. # 对于HTTP/SSE等远程传输,建议直接使用MCPClient
  17. from hello_agents.tools import MCPTool
  18. # 使用内置演示服务器(Memory传输)
  19. mcp_tool = MCPTool()
  20. # 列出可用工具
  21. result = mcp_tool.run({"action": "list_tools"})
  22. print(result)
  23. # 调用工具
  24. result = mcp_tool.run({
  25. "action": "call_tool",
  26. "tool_name": "add",
  27. "arguments": {"a": 10, "b": 20}
  28. })
  29. print(result)
  30. from hello_agents.tools import MCPTool
  31. # 方式1:使用自定义Python服务器
  32. mcp_tool = MCPTool(server_command=["python", "my_mcp_server.py"])
  33. # 方式2:使用社区服务器(文件系统)
  34. mcp_tool = MCPTool(server_command=["npx", "-y", "@modelcontextprotocol/server-filesystem", "."])
  35. # 列出工具
  36. result = mcp_tool.run({"action": "list_tools"})
  37. print(result)
  38. # 调用工具
  39. result = mcp_tool.run({
  40. "action": "call_tool",
  41. "tool_name": "read_file",
  42. "arguments": {"path": "my_README.md"}
  43. })
  44. print(result)
  45. # 注意:MCPTool 主要用于 Stdio 和 Memory 传输
  46. # 对于 HTTP/SSE 等远程传输,建议使用底层的 MCPClient
  47. import asyncio
  48. from hello_agents.protocols.mcp.client import MCPClient
  49. async def test_http_transport():
  50. # 连接到远程 HTTP MCP 服务器
  51. client = MCPClient("http://api.example.com/mcp")
  52. async with client:
  53. # 获取服务器信息
  54. tools = await client.list_tools()
  55. print(f"远程服务器工具: {len(tools)} 个")
  56. # 调用远程工具
  57. result = await client.call_tool("process_data", {
  58. "data": "Hello, World!",
  59. "operation": "uppercase"
  60. })
  61. print(f"远程处理结果: {result}")
  62. # 注意:需要实际的 HTTP MCP 服务器
  63. # asyncio.run(test_http_transport())