terminal_close
End and clean up a terminal session by specifying the session ID, ensuring efficient resource management and freeing up system capacity.
Instructions
Close a terminal session and cleanup resources
Args: session_id: ID of the terminal session
Returns: Dictionary with cleanup status
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| session_id | Yes |
Implementation Reference
- Core handler function for 'terminal_close' tool, registered via @mcp.tool() decorator. Validates session, calls cleanup on XTermSession, removes from global sessions dict, and returns status.@mcp.tool() async def terminal_close(session_id: str) -> Dict[str, Any]: """Close a terminal session and cleanup resources Args: session_id: ID of the terminal session Returns: Dictionary with cleanup status """ if session_id not in sessions: return {"status": "error", "error": f"Session {session_id} not found"} session = sessions[session_id] try: await session.cleanup() del sessions[session_id] logger.info(f"Closed terminal session {session_id}") return {"session_id": session_id, "status": "closed"} except Exception as e: logger.error(f"Failed to close session {session_id}: {e}") return {"status": "error", "error": str(e)}
- Helper method in XTermSession class that terminates the xterm and Xvfb subprocesses, cleans up temporary files, and finalizes session resources. Invoked by the terminal_close handler.async def cleanup(self): """Clean up processes and temporary files""" logger.debug(f"Cleaning up session {self.session_id}") self.is_running = False # Terminate xterm process if self.xterm_proc and self.xterm_proc.returncode is None: self.xterm_proc.terminate() try: await asyncio.wait_for(self.xterm_proc.wait(), timeout=5.0) except asyncio.TimeoutError: logger.warning("xterm process didn't terminate gracefully, killing it") self.xterm_proc.kill() await self.xterm_proc.wait() # Terminate Xvfb process if self.xvfb_proc and self.xvfb_proc.returncode is None: self.xvfb_proc.terminate() try: await asyncio.wait_for(self.xvfb_proc.wait(), timeout=5.0) except asyncio.TimeoutError: logger.warning("Xvfb process didn't terminate gracefully, killing it") self.xvfb_proc.kill() await self.xvfb_proc.wait() # Clean up temporary directory if self.temp_dir: try: import shutil shutil.rmtree(self.temp_dir, ignore_errors=True) self.temp_dir = None except Exception as e: logger.warning(f"Failed to clean up temp dir: {e}") # Small delay to let X server cleanup await asyncio.sleep(0.5) logger.info(f"Session {self.session_id} cleanup completed")