refactor: simplify error handling in MCP server code execution

This commit is contained in:
CaptainB 2025-08-12 17:38:35 +08:00
parent 5061708c1f
commit f0a3391897
2 changed files with 15 additions and 15 deletions

View File

@ -10,7 +10,9 @@ import asyncio
import json
import os
import re
import sys
import time
import traceback
from functools import reduce
from typing import List, Dict
@ -143,7 +145,7 @@ def mcp_response_generator(chat_model, message_list, mcp_servers):
except StopAsyncIteration:
break
except Exception as e:
maxkb_logger.error(f'Exception: {e}')
maxkb_logger.error(f'Exception: {e}', traceback.format_exc())
finally:
loop.close()
@ -285,9 +287,10 @@ class BaseChatNode(IChatNode):
code_path = f'{executor.sandbox_path}/execute/{tool_id}.py'
with open(code_path, 'w') as f:
f.write(code)
os.system(f"chown sandbox:root {code_path}")
tool_config = {
'command': 'python',
'command': sys.executable,
'args': [code_path],
'transport': 'stdio',
}

View File

@ -120,19 +120,16 @@ except Exception as e:
python_paths = CONFIG.get_sandbox_python_package_paths().split(',')
code = self._generate_mcp_server_code(code_str)
return f"""
try:
import os
import sys
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 += {python_paths}
env = dict(os.environ)
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'):
del os.environ[key]
exec({dedent(code)!a})
except Exception as e:
pass
import os
import sys
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 += {python_paths}
env = dict(os.environ)
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'):
del os.environ[key]
exec({dedent(code)!a})
"""
def _exec_sandbox(self, _code, _id):