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 json
import os import os
import re import re
import sys
import time import time
import traceback
from functools import reduce from functools import reduce
from typing import List, Dict from typing import List, Dict
@ -143,7 +145,7 @@ def mcp_response_generator(chat_model, message_list, mcp_servers):
except StopAsyncIteration: except StopAsyncIteration:
break break
except Exception as e: except Exception as e:
maxkb_logger.error(f'Exception: {e}') maxkb_logger.error(f'Exception: {e}', traceback.format_exc())
finally: finally:
loop.close() loop.close()
@ -285,9 +287,10 @@ class BaseChatNode(IChatNode):
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)
os.system(f"chown sandbox:root {code_path}")
tool_config = { tool_config = {
'command': 'python', 'command': sys.executable,
'args': [code_path], 'args': [code_path],
'transport': 'stdio', 'transport': 'stdio',
} }

View File

@ -120,7 +120,6 @@ except Exception as e:
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:
import os import os
import sys import sys
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']
@ -131,8 +130,6 @@ try:
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]
exec({dedent(code)!a}) exec({dedent(code)!a})
except Exception as e:
pass
""" """
def _exec_sandbox(self, _code, _id): def _exec_sandbox(self, _code, _id):