PersistentPythonSession#

class ansys.common.mcp.helpers.PersistentPythonSession(python_executable: str | None = None, startup_code: str | None = None, working_directory: str | None = None)#

Maintains a persistent Python subprocess for stateful code execution.

This class allows multiple code snippets to be executed in the same Python session, preserving variables, imports, and state between executions. This is essential for LLM workflows where code is generated and executed in multiple steps.

Parameters:
python_executablestr, default: None

Path to the Python executable to use. If None, sys.executable is used.

startup_codestr, default: None

Python code to execute when the session starts (for example, imports).

working_directorystr, default: None

Working directory for the Python process. If None, the current directory is used.

Examples

Create a persistent session and execute multiple steps:

>>> session = PersistentPythonSession()
>>> session.start()
>>>
>>> # Step 1: Define variables
>>> result = session.execute("x = 10; y = 20")
>>>
>>> # Step 2: Use those variables
>>> result = session.execute("z = x + y; print(z)")
>>> print(result["stdout"])  # 30
>>>
>>> session.stop()

Use with custom Python executable:

>>> session = PersistentPythonSession(
...     python_executable="/path/to/venv/bin/python",
...     startup_code="import numpy as np\\nimport pandas as pd",
... )

Overview#

start

Start the persistent Python session.

execute

Execute Python code in the persistent session.

stop

Stop the persistent Python session.

restart

Restart the persistent Python session.

is_running

Check if the session is currently running.

__enter__

Context manager entry.

__exit__

Context manager exit.

Import detail#

from ansys.common.mcp.helpers import PersistentPythonSession

Attribute detail#

PersistentPythonSession.python_executable = '/home/runner/work/pyansys-common-mcp/pyansys-common-mcp/.venv/bin/python3'#
PersistentPythonSession.startup_code = None#
PersistentPythonSession.working_directory = None#
PersistentPythonSession.process: subprocess.Popen | None = None#
PersistentPythonSession.metadata: dict[str, Any]#

Method detail#

PersistentPythonSession.start() dict[str, Any]#

Start the persistent Python session.

Returns:
dict[str, Any]

Dictionary with success status and any startup messages.

PersistentPythonSession.execute(code: str, timeout: float = 30.0) dict[str, Any]#

Execute Python code in the persistent session.

Parameters:
codestr

Python code to execute.

timeoutfloat, default: 30.0

Maximum execution time in seconds.

Returns:
dict[str, Any]

Dictionary containing: - ‘success’: Boolean indicating if execution succeeded - ‘stdout’: string with standard output - ‘stderr’: string with standard error - ‘error’: string with error message (if execution failed)

PersistentPythonSession.stop() dict[str, Any]#

Stop the persistent Python session.

Returns:
dict[str, Any]

Dictionary with success status and cleanup messages.

PersistentPythonSession.restart() dict[str, Any]#

Restart the persistent Python session.

Stops the current session (if running) and starts a new one. All session state (variables, imports) are lost except what’s recreated by startup_code.

This method is intended for manual restarts only. For example, use it when the session becomes unresponsive or when you want to reset the state. Command history and other application state should be managed at the application context level, not in the session itself.

Returns:
dict[str, Any]

Dictionary with success status and restart messages.

Notes

  • This is a manual operation. Automatic restart on crashes is NOT implemented.

  • Session state is lost (including variables and non-startup imports).

  • The startup_code is re-executed on restart.

  • Consider managing command_history at the context level for replay capability

Examples

Basic restart:

>>> session = PersistentPythonSession()
>>> session.start()
>>> # ... do some work ...
>>> result = session.restart()
>>> if result["success"]:
...     print("Session restarted")

In an MCP tool with command replay:

>>> # Get context
>>> ctx = get_context()
>>> app_context = ctx.fastmcp._lifespan_result
>>>
>>> # Restart session
>>> restart_result = app_context.python_session.restart()
>>>
>>> # Optionally replay command history
>>> if restart_result["success"] and app_context.command_history:
...     for cmd in app_context.command_history:
...         app_context.python_session.execute(cmd)
PersistentPythonSession.is_running() bool#

Check if the session is currently running.

Returns:
bool

True if session is running, False otherwise.

PersistentPythonSession.__enter__()#

Context manager entry.

PersistentPythonSession.__exit__(_exc_type, _exc_val, _exc_tb)#

Context manager exit.