|
16 | 16 | from functools import reduce |
17 | 17 | from typing import List, Dict |
18 | 18 |
|
| 19 | +import uuid_utils.compat as uuid |
19 | 20 | from django.db.models import QuerySet |
20 | 21 | from langchain.schema import HumanMessage, SystemMessage |
21 | 22 | from langchain_core.messages import BaseMessage, AIMessage, AIMessageChunk, ToolMessage |
|
27 | 28 | from application.flow.tools import Reasoning |
28 | 29 | from common.utils.logger import maxkb_logger |
29 | 30 | from common.utils.tool_code import ToolExecutor |
30 | | -from maxkb.conf import PROJECT_DIR |
31 | 31 | from models_provider.models import Model |
32 | 32 | from models_provider.tools import get_model_credential, get_model_instance_by_model_workspace_id |
33 | 33 | from tools.models import Tool |
@@ -280,18 +280,26 @@ def _handle_mcp_request(self, mcp_enable, tool_enable, mcp_source, mcp_servers, |
280 | 280 | if tool_enable: |
281 | 281 | if tool_ids and len(tool_ids) > 0: # 如果有工具ID,则将其转换为MCP |
282 | 282 | self.context['tool_ids'] = tool_ids |
| 283 | + self.context['execute_ids'] = [] |
283 | 284 | for tool_id in tool_ids: |
284 | 285 | tool = QuerySet(Tool).filter(id=tool_id).first() |
285 | | - executor = ToolExecutor() |
| 286 | + executor = ToolExecutor(sandbox=True) |
286 | 287 | code = executor.generate_mcp_server_code(tool.code) |
287 | | - code_path = f'{executor.sandbox_path}/execute/{tool_id}.py' |
| 288 | + _id = uuid.uuid7() |
| 289 | + self.context['execute_ids'].append(_id) |
| 290 | + code_path = f'{executor.sandbox_path}/execute/{_id}.py' |
288 | 291 | with open(code_path, 'w') as f: |
289 | 292 | f.write(code) |
290 | | - os.system(f"chown sandbox:root {code_path}") |
| 293 | + os.system(f"chown {executor.user}:root {code_path}") |
291 | 294 |
|
292 | 295 | tool_config = { |
293 | | - 'command': sys.executable, |
294 | | - 'args': [code_path], |
| 296 | + 'command': 'su', |
| 297 | + 'args': [ |
| 298 | + '-s', sys.executable, |
| 299 | + '-c', f"exec(open('{code_path}', 'r').read())", |
| 300 | + executor.user, |
| 301 | + ], |
| 302 | + 'cwd': executor.sandbox_path, |
295 | 303 | 'transport': 'stdio', |
296 | 304 | } |
297 | 305 | mcp_servers_config[str(tool.id)] = tool_config |
@@ -338,10 +346,10 @@ def reset_message_list(message_list: List[BaseMessage], answer_text): |
338 | 346 |
|
339 | 347 | def get_details(self, index: int, **kwargs): |
340 | 348 | # 删除临时生成的MCP代码文件 |
341 | | - if self.context.get('tool_ids'): |
342 | | - executor = ToolExecutor() |
| 349 | + if self.context.get('execute_ids'): |
| 350 | + executor = ToolExecutor(sandbox=True) |
343 | 351 | # 清理工具代码文件,延时删除,避免文件被占用 |
344 | | - for tool_id in self.context.get('tool_ids'): |
| 352 | + for tool_id in self.context.get('execute_ids'): |
345 | 353 | code_path = f'{executor.sandbox_path}/execute/{tool_id}.py' |
346 | 354 | if os.path.exists(code_path): |
347 | 355 | os.remove(code_path) |
|
0 commit comments