server_a2a.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import logging
  2. import uvicorn
  3. from python_a2a.mcp import FastMCP
  4. from python_a2a.mcp import create_fastapi_app
  5. # 配置日志,方便调试
  6. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  7. logger = logging.getLogger(__name__)
  8. # 创建 MCP 服务器实例
  9. mcp = FastMCP(
  10. name="MyMCPTools",
  11. description="提供高频问题和天气查询工具",
  12. version="1.0.0"
  13. )
  14. # 定义工具 1:查询高频问题
  15. @mcp.tool(
  16. name="query_high_frequency_question",
  17. description="获取知识库中的高频问答,返回 JSON 数据",
  18. )
  19. async def query_high_frequency_question() -> str:
  20. """
  21. query_high_frequency_question 不需要任何传参
  22. 查询高频问题并返回答案
  23. 返回示例:[{"question_id": 1, "question_text": "恐龙怎么灭绝", "answer_text": "小行星撞击", ...}]
  24. """
  25. try:
  26. logger.info("调用查询高频问题的工具(无参数)")
  27. return '{"status": "success", "data": [{"question_id": 1, "question_text": "恐龙是怎么灭绝的?", "answer_text": "可能是小行星撞击", "category": "历史", "frequency_score": 0.9}]}'
  28. except Exception as e:
  29. logger.error(f"查询高频问题出错: {str(e)}")
  30. raise
  31. # 定义工具 2:查询天气
  32. @mcp.tool(
  33. name="get_weather",
  34. description="查询天气",
  35. )
  36. async def get_weather() -> str:
  37. """
  38. get_weather 不需要任何传参
  39. 查询天气并返回结果
  40. 返回示例:{"status": "success", "data": "北京的天气是多云"}
  41. """
  42. try:
  43. logger.info("调用查询天气的工具(无参数)")
  44. return '{"status": "success", "data": "北京的天气是多云"}'
  45. except Exception as e:
  46. logger.error(f"查询天气出错: {str(e)}")
  47. raise
  48. # 启动服务器
  49. def start_server():
  50. logger.info("=== MCP 服务器信息 ===")
  51. logger.info(f"名称: {mcp.name}")
  52. logger.info(f"描述: {mcp.description}")
  53. port = 8010
  54. app = create_fastapi_app(mcp)
  55. logger.info(f"启动 MCP 服务器于 http://localhost:{port}")
  56. uvicorn.run(app, host="0.0.0.0", port=port)
  57. if __name__ == "__main__":
  58. start_server()