MCPcopy Create free account
hub / github.com/modelscope/ms-agent / connect

Method connect

ms_agent/tools/code/code_executor.py:203–314  ·  view source on GitHub ↗

Initialize sandbox manager and create sandbox instance with automatic port retry

(self)

Source from the content-addressed store, hash-verified

201 raise ValueError(f'Unknown sandbox type: {self.sandbox_type}')
202
203 async def connect(self) -> None:
204 """Initialize sandbox manager and create sandbox instance with automatic port retry"""
205 from ms_enclave.sandbox.model import SandboxType
206
207 if self._initialized:
208 logger.debug('Sandbox already initialized')
209 return
210
211 try:
212 logger.info('Initializing sandbox manager...')
213
214 # Create manager using factory
215 self.manager = await SandboxManagerFactory.create_manager(
216 self.config)
217 await self.manager.start()
218
219 logger.info('Creating sandbox instance...')
220
221 # Try to create sandbox with port retry logic
222 retry_count = 0
223 max_retries = self._max_port_retries if self._port_retry_enabled else 1
224 last_error = None
225
226 while retry_count < max_retries:
227 try:
228 self.sandbox_id = await self.manager.create_sandbox(
229 sandbox_type=self.sandbox_type,
230 config=self.sandbox_config)
231
232 logger.info(f'Sandbox created: {self.sandbox_id}')
233
234 # Wait for sandbox to be ready
235 await self._wait_for_sandbox_ready()
236
237 self._initialized = True
238 logger.info('Sandbox is ready for code execution')
239 return
240
241 except Exception as e:
242 error_msg = str(e).lower()
243 last_error = e
244
245 # Check if it's a port conflict error
246 is_port_conflict = any(keyword in error_msg
247 for keyword in [
248 'address already in use',
249 'port is already allocated',
250 'bind: address already in use',
251 'port already in use'
252 ])
253
254 if is_port_conflict and self._port_retry_enabled and retry_count < (
255 max_retries - 1):
256 retry_count += 1
257 logger.warning(
258 f'Port conflict detected (attempt {retry_count}/{max_retries}): {e}'
259 )
260

Callers 1

call_toolMethod · 0.95

Calls 4

find_available_portFunction · 0.85
create_managerMethod · 0.80
startMethod · 0.45

Tested by

no test coverage detected