Browse Source

新增mcp_git功能

fulian23 3 months ago
parent
commit
bfa552455c
3 changed files with 40 additions and 32 deletions
  1. 14 0
      api/aiRouter.py
  2. 25 31
      mcp_/client.py
  3. 1 1
      mcp_/server.py

+ 14 - 0
api/aiRouter.py

@@ -10,6 +10,8 @@ from dashscope import Application
 
 from models.aiModels import Scan_Tasks, Commit_Summary_Tasks, File_Summary_Tasks
 
+from mcp_.client import MCPClient
+
 airouter = APIRouter()
 class RequestCommit(BaseModel):
     task_id: str
@@ -27,6 +29,10 @@ class RequestFile(BaseModel):
     repo_url: str
     file_path: str
 
+class RequestChat(BaseModel):
+    uuid: str
+    message: str
+
 def generate_repo_path(uuid, repo_url):
     repo_name = repo_url.split("/")[-1].replace(".git", "")
     base_path = os.path.join(path, uuid)
@@ -249,6 +255,14 @@ async def summaryFile(request: RequestFile,background_tasks: BackgroundTasks):
     background_tasks.add_task(file_task, request.file_path, request.task_id)
     return {"code": 200, "msg": "添加提交任务成功"}
 
+@airouter.post("/chat")
+async def chat(request: RequestChat):
+    client = MCPClient(request.uuid)
+    await client.connect_to_server()
+    response = await client.process_query(request.message)
+    await client.cleanup()
+    return {"code": 200, "msg": response}
+
 
 
 

+ 25 - 31
mcp/client.py → mcp_/client.py

@@ -11,34 +11,38 @@ from dashscope import Application, Generation
 
 # load_dotenv()
 
-SCRIPT_PATH = "server.py"
 
-SYSTEM_PROMPT = """您是一个可执行git操作的AI助手,可用工具:
+
+
+class MCPClient:
+    def __init__(self,session_id):
+        self.session: Optional[ClientSession] = None
+        self.exit_stack = AsyncExitStack()
+        self.session_id = session_id
+        self.api_key = "sk-0164613e1a2143fc808fc4cc2451bef0"
+        self.app_id = "b424f3fa1d4544d68579671d70596f29"
+        self.model = "qwen-max"
+        self.SCRIPT_PATH = "mcp_/server.py"
+        self.SYSTEM_PROMPT = """
+您是一个可执行git操作的AI助手,可用工具:
 {tools_description}
 
 响应规则:
+
 1. 需要工具时必须返回严格JSON格式:
 {{
     "tool": "工具名",
     "arguments": {{参数键值对}}
 }}
 2. 不需要工具时直接回复自然语言
-3. 工具列表:
+3. 仓库都在C:\\www\\gitnexus\\{uuid}
+4. 工具列表:
 {available_tools}"""
-class MCPClient:
-    def __init__(self):
-        self.session: Optional[ClientSession] = None
-        self.exit_stack = AsyncExitStack()
-        self.session_id = None
-        self.api_key = "sk-0164613e1a2143fc808fc4cc2451bef0"
-        self.app_id = "b424f3fa1d4544d68579671d70596f29"
-        self.model = "qwen-max"
-        self.SYSTEM_PROMPT = SYSTEM_PROMPT
 
     async def connect_to_server(self):
         server_params = StdioServerParameters(
             command="python",
-            args=[SCRIPT_PATH]
+            args=[self.SCRIPT_PATH]
         )
         stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
         self.stdio, self.write = stdio_transport
@@ -59,7 +63,8 @@ class MCPClient:
 
             full_prompt = self.SYSTEM_PROMPT.format(
                 tools_description=tools_desc,
-                available_tools=[t.name for t in tool_response.tools]
+                available_tools=[t.name for t in tool_response.tools],
+                uuid=self.session_id
             )
 
             response = await asyncio.to_thread(
@@ -73,10 +78,6 @@ class MCPClient:
                 enable_mcp=True,
                 tool_choice="auto"
             )
-            print(full_prompt + "\n用户提问:" + prompt)
-            if response.output.session_id:
-                self.session_id = response.output.session_id
-
             if response.status_code == HTTPStatus.OK:
                 return response.output.text
             return f"API Error: {response.message}"
@@ -102,20 +103,13 @@ class MCPClient:
 
     async def chat_loop(self):
         print("\nMCP Client Started!")
-        print("Type your queries or 'quit' to exit.")
-
-        while True:
-            try:
-                query = input("\nQuery: ").strip()
-
-                if query.lower() == 'quit':
-                    break
-
-                response = await self.process_query(query)
-                print("\n" + response)
+        try:
+            query = input("\nQuery: ").strip()
+            response = await self.process_query(query)
+            print("\n" + response)
 
-            except Exception as e:
-                print(f"\nError: {str(e)}")
+        except Exception as e:
+            print(f"\nError: {str(e)}")
 
     async def cleanup(self):
         await self.exit_stack.aclose()

+ 1 - 1
mcp/server.py → mcp_/server.py

@@ -208,7 +208,7 @@ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(level
 # Initialize MCPFast
 mcp = FastMCP("git")
 
-# --- Tool Definitions using @mcp.tool() ---
+# --- Tool Definitions using @mcp_.tool() ---
 
 @mcp.tool()
 async def init_tool(repo_path: str) -> list[TextContent]: