02_Connect2MCP.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import asyncio
  2. from hello_agents.protocols import MCPClient
  3. async def connect_to_server():
  4. # 方式1:连接到社区提供的文件系统服务器
  5. # npx会自动下载并运行@modelcontextprotocol/server-filesystem包
  6. client = MCPClient([
  7. "npx", "-y",
  8. "@modelcontextprotocol/server-filesystem",
  9. "." # 指定根目录
  10. ])
  11. # 使用async with确保连接正确关闭
  12. async with client:
  13. # 在这里使用client
  14. tools = await client.list_tools()
  15. print(f"可用工具: {[t['name'] for t in tools]}")
  16. # 方式2:连接到自定义的Python MCP服务器
  17. client = MCPClient(["python", "my_mcp_server.py"])
  18. async with client:
  19. # 使用client...
  20. pass
  21. # 运行异步函数
  22. asyncio.run(connect_to_server())
  23. async def discover_tools():
  24. client = MCPClient(["npx", "-y", "@modelcontextprotocol/server-filesystem", "."])
  25. async with client:
  26. # 获取所有可用工具
  27. tools = await client.list_tools()
  28. print(f"服务器提供了 {len(tools)} 个工具:")
  29. for tool in tools:
  30. print(f"\n工具名称: {tool['name']}")
  31. print(f"描述: {tool.get('description', '无描述')}")
  32. # 打印参数信息
  33. if 'inputSchema' in tool:
  34. schema = tool['inputSchema']
  35. if 'properties' in schema:
  36. print("参数:")
  37. for param_name, param_info in schema['properties'].items():
  38. param_type = param_info.get('type', 'any')
  39. param_desc = param_info.get('description', '')
  40. print(f" - {param_name} ({param_type}): {param_desc}")
  41. asyncio.run(discover_tools())
  42. # 输出示例:
  43. # 服务器提供了 5 个工具:
  44. #
  45. # 工具名称: read_file
  46. # 描述: 读取文件内容
  47. # 参数:
  48. # - path (string): 文件路径
  49. #
  50. # 工具名称: write_file
  51. # 描述: 写入文件内容
  52. # 参数:
  53. # - path (string): 文件路径
  54. # - content (string): 文件内容
  55. async def use_tools():
  56. client = MCPClient(["npx", "-y", "@modelcontextprotocol/server-filesystem", "."])
  57. async with client:
  58. # 读取文件
  59. result = await client.call_tool("read_file", {"path": "my_README.md"})
  60. print(f"文件内容:\n{result}")
  61. # 列出目录
  62. result = await client.call_tool("list_directory", {"path": "."})
  63. print(f"当前目录文件:{result}")
  64. # 写入文件
  65. result = await client.call_tool("write_file", {
  66. "path": "output.txt",
  67. "content": "Hello from MCP!"
  68. })
  69. print(f"写入结果:{result}")
  70. asyncio.run(use_tools())
  71. async def safe_tool_call():
  72. client = MCPClient(["npx", "-y", "@modelcontextprotocol/server-filesystem", "."])
  73. async with client:
  74. try:
  75. # 尝试读取可能不存在的文件
  76. result = await client.call_tool("read_file", {"path": "nonexistent.txt"})
  77. print(result)
  78. except Exception as e:
  79. print(f"工具调用失败: {e}")
  80. # 可以选择重试、使用默认值或向用户报告错误
  81. asyncio.run(safe_tool_call())