Skip to content

Commit bb665b5

Browse files
committed
feat: enhance MCP tool execution with unique ID generation and improved file handling
1 parent f0a3391 commit bb665b5

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

apps/application/flow/step_node/ai_chat_step_node/impl/base_chat_node.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from functools import reduce
1717
from typing import List, Dict
1818

19+
import uuid_utils.compat as uuid
1920
from django.db.models import QuerySet
2021
from langchain.schema import HumanMessage, SystemMessage
2122
from langchain_core.messages import BaseMessage, AIMessage, AIMessageChunk, ToolMessage
@@ -27,7 +28,6 @@
2728
from application.flow.tools import Reasoning
2829
from common.utils.logger import maxkb_logger
2930
from common.utils.tool_code import ToolExecutor
30-
from maxkb.conf import PROJECT_DIR
3131
from models_provider.models import Model
3232
from models_provider.tools import get_model_credential, get_model_instance_by_model_workspace_id
3333
from tools.models import Tool
@@ -280,18 +280,26 @@ def _handle_mcp_request(self, mcp_enable, tool_enable, mcp_source, mcp_servers,
280280
if tool_enable:
281281
if tool_ids and len(tool_ids) > 0: # 如果有工具ID,则将其转换为MCP
282282
self.context['tool_ids'] = tool_ids
283+
self.context['execute_ids'] = []
283284
for tool_id in tool_ids:
284285
tool = QuerySet(Tool).filter(id=tool_id).first()
285-
executor = ToolExecutor()
286+
executor = ToolExecutor(sandbox=True)
286287
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'
288291
with open(code_path, 'w') as f:
289292
f.write(code)
290-
os.system(f"chown sandbox:root {code_path}")
293+
os.system(f"chown {executor.user}:root {code_path}")
291294

292295
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,
295303
'transport': 'stdio',
296304
}
297305
mcp_servers_config[str(tool.id)] = tool_config
@@ -338,10 +346,10 @@ def reset_message_list(message_list: List[BaseMessage], answer_text):
338346

339347
def get_details(self, index: int, **kwargs):
340348
# 删除临时生成的MCP代码文件
341-
if self.context.get('tool_ids'):
342-
executor = ToolExecutor()
349+
if self.context.get('execute_ids'):
350+
executor = ToolExecutor(sandbox=True)
343351
# 清理工具代码文件,延时删除,避免文件被占用
344-
for tool_id in self.context.get('tool_ids'):
352+
for tool_id in self.context.get('execute_ids'):
345353
code_path = f'{executor.sandbox_path}/execute/{tool_id}.py'
346354
if os.path.exists(code_path):
347355
os.remove(code_path)

0 commit comments

Comments
 (0)