Skip to content

Commit 1d7a5af

Browse files
committed
feat: refactor MCP server code generation and add execution method
1 parent f2459ed commit 1d7a5af

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from application.flow.tools import Reasoning
2626
from common.utils.logger import maxkb_logger
2727
from common.utils.tool_code import ToolExecutor
28+
from maxkb.conf import PROJECT_DIR
2829
from models_provider.models import Model
2930
from models_provider.tools import get_model_credential, get_model_instance_by_model_workspace_id
3031
from tools.models import Tool
@@ -280,7 +281,7 @@ def _handle_mcp_request(self, mcp_enable, tool_enable, mcp_source, mcp_servers,
280281
for tool_id in tool_ids:
281282
tool = QuerySet(Tool).filter(id=tool_id).first()
282283
executor = ToolExecutor()
283-
code = executor.generate_mcp_server_code(tool.code)
284+
code = executor.get_exec_code(tool.code)
284285
code_path = f'{executor.sandbox_path}/execute/{tool_id}.py'
285286
with open(code_path, 'w') as f:
286287
f.write(code)

apps/common/utils/tool_code.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def exec_code(self, code_str, keywords):
8383
return result.get('data')
8484
raise Exception(result.get('msg'))
8585

86-
def generate_mcp_server_code(self, _code):
86+
def _generate_mcp_server_code(self, _code):
8787
self.validate_banned_keywords(_code)
8888

8989
# 解析代码,提取导入语句和函数定义
@@ -116,6 +116,31 @@ def generate_mcp_server_code(self, _code):
116116

117117
return "\n".join(code_parts)
118118

119+
def get_exec_code(self, code_str):
120+
python_paths = CONFIG.get_sandbox_python_package_paths().split(',')
121+
code = self._generate_mcp_server_code(code_str)
122+
return f"""
123+
try:
124+
import os
125+
import sys
126+
import pickle
127+
path_to_exclude = ['/opt/py3/lib/python3.11/site-packages', '/opt/maxkb-app/apps']
128+
sys.path = [p for p in sys.path if p not in path_to_exclude]
129+
sys.path += {python_paths}
130+
env = dict(os.environ)
131+
for key in list(env.keys()):
132+
if key in os.environ and (key.startswith('MAXKB') or key.startswith('POSTGRES') or key.startswith('PG') or key.startswith('REDIS') or key == 'PATH'):
133+
del os.environ[key]
134+
locals_v={'{}'}
135+
globals_v=globals()
136+
exec({dedent(code)!a}, globals_v, locals_v)
137+
f_name, f = locals_v.popitem()
138+
for local in locals_v:
139+
globals_v[local] = locals_v[local]
140+
except Exception as e:
141+
pass
142+
"""
143+
119144
def _exec_sandbox(self, _code, _id):
120145
exec_python_file = f'{self.sandbox_path}/execute/{_id}.py'
121146
with open(exec_python_file, 'w') as file:

0 commit comments

Comments
 (0)