feat: refactor MCP code generation and update cleanup logic

This commit is contained in:
CaptainB 2025-08-12 17:22:24 +08:00
parent 1837512abc
commit 541f1f26c8
2 changed files with 5 additions and 11 deletions

View File

@ -281,7 +281,7 @@ class BaseChatNode(IChatNode):
for tool_id in tool_ids: for tool_id in tool_ids:
tool = QuerySet(Tool).filter(id=tool_id).first() tool = QuerySet(Tool).filter(id=tool_id).first()
executor = ToolExecutor() executor = ToolExecutor()
code = executor.get_exec_code(tool.code) code = executor.generate_mcp_server_code(tool.code)
code_path = f'{executor.sandbox_path}/execute/{tool_id}.py' code_path = f'{executor.sandbox_path}/execute/{tool_id}.py'
with open(code_path, 'w') as f: with open(code_path, 'w') as f:
f.write(code) f.write(code)
@ -340,8 +340,8 @@ class BaseChatNode(IChatNode):
# 清理工具代码文件,延时删除,避免文件被占用 # 清理工具代码文件,延时删除,避免文件被占用
for tool_id in self.context.get('tool_ids'): for tool_id in self.context.get('tool_ids'):
code_path = f'{executor.sandbox_path}/execute/{tool_id}.py' code_path = f'{executor.sandbox_path}/execute/{tool_id}.py'
if os.path.exists(code_path): # if os.path.exists(code_path):
os.remove(code_path) # os.remove(code_path)
return { return {
'name': self.node.properties.get('stepName'), 'name': self.node.properties.get('stepName'),
"index": index, "index": index,

View File

@ -116,14 +116,13 @@ except Exception as e:
return "\n".join(code_parts) return "\n".join(code_parts)
def get_exec_code(self, code_str): def generate_mcp_server_code(self, code_str):
python_paths = CONFIG.get_sandbox_python_package_paths().split(',') python_paths = CONFIG.get_sandbox_python_package_paths().split(',')
code = self._generate_mcp_server_code(code_str) code = self._generate_mcp_server_code(code_str)
return f""" return f"""
try: try:
import os import os
import sys import sys
import pickle
path_to_exclude = ['/opt/py3/lib/python3.11/site-packages', '/opt/maxkb-app/apps'] path_to_exclude = ['/opt/py3/lib/python3.11/site-packages', '/opt/maxkb-app/apps']
sys.path = [p for p in sys.path if p not in path_to_exclude] sys.path = [p for p in sys.path if p not in path_to_exclude]
sys.path += {python_paths} sys.path += {python_paths}
@ -131,12 +130,7 @@ try:
for key in list(env.keys()): for key in list(env.keys()):
if key in os.environ and (key.startswith('MAXKB') or key.startswith('POSTGRES') or key.startswith('PG') or key.startswith('REDIS') or key == 'PATH'): if key in os.environ and (key.startswith('MAXKB') or key.startswith('POSTGRES') or key.startswith('PG') or key.startswith('REDIS') or key == 'PATH'):
del os.environ[key] del os.environ[key]
locals_v={'{}'} exec({dedent(code)!a})
globals_v=globals()
exec({dedent(code)!a}, globals_v, locals_v)
f_name, f = locals_v.popitem()
for local in locals_v:
globals_v[local] = locals_v[local]
except Exception as e: except Exception as e:
pass pass
""" """