server.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import asyncio
  2. import json
  3. from typing import Any, Dict, List
  4. import mcp.types as types
  5. from mcp.server.lowlevel import Server
  6. from applications.resource import get_resource_manager
  7. from applications.utils.chat import RAGChatAgent
  8. from applications.utils.mysql import ChatResult
  9. from applications.api.qwen import QwenClient
  10. from applications.utils.spider.study import study
  11. from applications.utils.task.async_task import query_search, process_question
  12. def create_mcp_server() -> Server:
  13. """创建并配置MCP服务器"""
  14. app = Server("mcp-rag-server")
  15. @app.call_tool()
  16. async def call_tool(
  17. name: str, arguments: Dict[str, Any]
  18. ) -> List[types.TextContent]:
  19. """处理工具调用"""
  20. # ctx = app.request_context
  21. if name == "rag-search":
  22. data = await rag_search(arguments["query_text"])
  23. result = json.dumps(data, ensure_ascii=False, indent=2)
  24. else:
  25. raise ValueError(f"Unknown tool: {name}")
  26. return [types.TextContent(type="text", text=result)]
  27. @app.list_tools()
  28. async def list_tools() -> List[types.Tool]:
  29. return [
  30. types.Tool(
  31. name="rag-search",
  32. title="RAG搜索",
  33. description="搜索内容并生成总结",
  34. inputSchema={
  35. "type": "object",
  36. "properties": {
  37. "query_text": {
  38. "type": "string",
  39. "description": "用户输入的查询文本",
  40. }
  41. },
  42. "required": ["query_text"], # 只强制 query_text 必填
  43. "additionalProperties": False,
  44. },
  45. ),
  46. ]
  47. return app
  48. async def rag_search(query_text: str):
  49. rag_chat_agent = RAGChatAgent()
  50. split_questions = []
  51. # spilt_query = await rag_chat_agent.split_query(query_text)
  52. # split_questions = spilt_query["split_questions"]
  53. split_questions.append(query_text)
  54. resource = get_resource_manager()
  55. qwen_client = QwenClient()
  56. rag_chat_agent = RAGChatAgent()
  57. # 使用asyncio.gather并行处理每个问题
  58. tasks = [
  59. process_question(question, resource, qwen_client, rag_chat_agent)
  60. for question in split_questions
  61. ]
  62. # 等待所有任务完成并收集结果
  63. data_list = await asyncio.gather(*tasks)
  64. return data_list