# Directory Structure
```
├── .gitignore
├── LICENSE
├── mcp_server.py
├── README_zh.md
├── README.md
├── requirements.txt
└── test_mcp_server.py
```
# Files
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
```
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/version info into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
osetests.xml
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# PEP 582; Pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype
.pytype/
# IDE / Editor specific
.vscode/
.idea/
*.suo
*.ntvs*.*
*.njsproj
*.sln
*.sublime-project
*.sublime-workspace
# OS specific
.DS_Store
Thumbs.db
```
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
```markdown
English | [中文](README_zh.md)
# ABAQUS MCP Server for GUI Scripting
An MCP (Model Context Protocol) server designed to interact with an **already running** Abaqus/CAE Graphical User Interface (GUI). It allows for the execution of Python scripts within the Abaqus environment and retrieval of messages from the Abaqus message log/area, all through MCP tools.
This server uses GUI automation techniques (`pywinauto`) to control the Abaqus/CAE application.
## Features
- **Script Execution in GUI**: Executes Python scripts by automating the "File -> Run Script..." menu in an active Abaqus/CAE session.
- **Message Log Retrieval**: Attempts to scrape text content from the Abaqus/CAE message/log display area.
- **MCP Interface**: Exposes functionalities as standard MCP tools and prompts for easy integration with LLM agents and other MCP-compatible clients.
- **Operates on Existing GUI**: Does not start or stop Abaqus/CAE; it requires an Abaqus/CAE session to be already open and running.
## System Requirements
- **Operating System**: Windows (due to `pywinauto` and Abaqus GUI interaction).
- **Python**: Python 3.7+.
- **Abaqus/CAE**: A compatible version of Abaqus/CAE must be installed and **already running with its GUI open** when using this server.
## Python Dependencies
Install the required Python packages using pip:
```bash
pip install -r requirements.txt
```
(See `requirements.txt` for the list of dependencies, primarily `mcp[cli]`, `pywinauto`, `pygetwindow`, `psutil`, `pywin32`.)
## Configuration
1. **Ensure Abaqus/CAE is Running**: Before starting this MCP server, make sure the Abaqus/CAE application is open on your desktop, with the GUI loaded and responsive.
2. **Accessibility**: Ensure no other modal dialogs are blocking the Abaqus/CAE interface when the server attempts to interact with it.
## Usage
### Starting the MCP Server
Navigate to the server's directory and run:
```bash
python mcp_server.py
```
The server will start and be ready to accept MCP requests.
### MCP Tools Provided
1. **`execute_script_in_abaqus_gui`**
* **Description**: Executes a given Python code string within the active Abaqus/CAE GUI session. It automates the 'File -> Run Script...' menu process.
* **Argument**:
* `python_code (str)`: The Python script content (Abaqus Scripting Interface commands) to be executed.
* **Returns**: `str` - A message indicating the outcome of the script *submission* attempt (e.g., "Script submitted for execution...").
* **Important**: This tool **does not** return the direct output or error messages from the script's execution within Abaqus. To see the script's actual outcome, you must use the `get_abaqus_gui_message_log` tool after allowing time for the script to run.
2. **`get_abaqus_gui_message_log`**
* **Description**: Attempts to retrieve the text content from the Abaqus/CAE message/log area (usually found at the bottom of the main GUI window).
* **Arguments**: None.
* **Returns**: `str` - The extracted text from the message area, or an error/status message if retrieval fails.
* **Note**: The reliability of this tool depends on accurately identifying the message area UI element. The current implementation uses heuristics. For robust operation in a specific Abaqus environment, you might need to update the server code with specific UI element identifiers (e.g., AutomationId, Name, ClassName) obtained using an inspect tool (see Development/Troubleshooting).
### MCP Prompts Provided
1. **`abaqus_scripting_strategy`**
* **Description**: This prompt provides comprehensive guidance on how to best use the server's tools (`execute_script_in_abaqus_gui` and `get_abaqus_gui_message_log`) together effectively. It explains the workflow for script execution and result verification, tool assumptions, and troubleshooting tips. It is highly recommended that LLM agents consult this prompt before attempting to use the tools.
## Important Considerations & Limitations
- **Requires Running Abaqus GUI**: This server *only* interacts with an Abaqus/CAE session that is already open and has its GUI active and responsive. It cannot start or manage the Abaqus application itself.
- **GUI Automation Sensitivity**: GUI automation can be sensitive to the Abaqus version, screen resolution, window themes, and minor UI layout changes. While `pywinauto` provides a good level of abstraction, issues can still arise.
- **Focus and Window State**: The Abaqus window should ideally be the active, non-minimized window for the most reliable interaction, although the server attempts to manage focus.
- **Modal Dialogs**: Unexpected modal dialogs in Abaqus (e.g., save reminders, warnings) can block the automation tools.
- **Error Reporting**: Differentiate between errors from the MCP tools (e.g., "Abaqus window not found") and errors reported *within* the Abaqus message log (which originate from your script running inside Abaqus).
## Development / Troubleshooting
- **Inspecting UI Elements**: If the `get_abaqus_gui_message_log` tool fails to retrieve messages accurately, or if `execute_script_in_abaqus_gui` has trouble with the "Run Script" dialog, you may need to use a UI inspection tool (e.g., `pywinauto.inspect` module's `InspectDialog` or `py_inspect.py` script, FlaUInspect for UIA backend) to identify the correct properties (AutomationId, Name, ClassName, ControlType) of the target UI elements in your Abaqus version. These properties can then be used to refine the search logic in `mcp_server.py`.
- **Timeouts**: The server includes some `time.sleep()` calls and uses `pywinauto`'s `Timings.slow()` to better handle Abaqus's potentially slow UI response times. These might need adjustment in some environments.
## Project Structure
```
abaqus-mcp-gui-server/
├── mcp_server.py # The main MCP server script
├── requirements.txt # Python dependencies
└── README.md # This documentation file
```
## License
This project is intended for learning, research, and specific automation tasks. When using Abaqus software, always adhere to the licensing terms provided by Dassault Systèmes.
```
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
```
mcp[cli]
pywinauto
pygetwindow
psutil
pywin32
```
--------------------------------------------------------------------------------
/test_mcp_server.py:
--------------------------------------------------------------------------------
```python
import unittest
from unittest.mock import patch, MagicMock
import os
import sys
# Add the directory containing mcp_server.py to the Python path
# This is to ensure that the mcp_server module can be imported
# Assuming test_mcp_server.py is in the same directory as mcp_server.py
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
try:
from mcp_server import (
find_abaqus_window_and_app,
execute_script,
get_abaqus_message_log,
mcp # For FastMCP instance if needed for context, though tools are standalone
)
# Mock a dummy FastMCP instance for the decorators to work if they rely on it at import time
# This might not be strictly necessary if the functions can be tested in isolation
# but good for ensuring the module loads.
if not hasattr(mcp, 'tool'): # If mcp was not fully initialized for some reason
class DummyMCP:
def tool(self, *args, **kwargs):
def decorator(f):
return f
return decorator
def prompt(self, *args, **kwargs):
def decorator(f):
return f
return decorator
mcp = DummyMCP()
except ImportError as e:
print(f"Failed to import from mcp_server: {e}")
# Define dummy functions if import fails, so tests can at least be defined
def find_abaqus_window_and_app(): pass
def execute_script(python_code: str): pass
def get_abaqus_message_log(): pass
class TestFindAbaqusWindowAndApp(unittest.TestCase):
@patch('mcp_server.gw')
@patch('mcp_server.win32process')
@patch('mcp_server.psutil')
@patch('mcp_server.Application')
@patch('mcp_server.abaqus_app_instance_cache', new=None)
@patch('mcp_server.abaqus_main_window_cache', new=None)
def test_find_window_success_no_cache(self, mock_app_class, mock_psutil, mock_win32process, mock_gw):
# Setup mocks for a successful window find and connection
mock_window_ref = MagicMock()
mock_window_ref.title = "Abaqus/CAE ModName - JobName"
mock_window_ref._hWnd = 12345
mock_gw.getWindowsWithTitle.return_value = [mock_window_ref]
mock_win32process.GetWindowThreadProcessId.return_value = (None, 67890)
mock_proc = MagicMock()
mock_proc.name.return_value = "abaqus_cae.exe"
mock_psutil.Process.return_value = mock_proc
mock_pywinauto_app = MagicMock()
mock_main_window_spec = MagicMock()
mock_main_window_spec.exists.return_value = True
mock_main_window_spec.is_visible.return_value = True
mock_pywinauto_app.window.return_value = mock_main_window_spec
mock_app_class.return_value.connect.return_value = mock_pywinauto_app # connect() returns the app instance
# Simulate that app.window() is called on the instance returned by connect()
# If connect() returns the app instance, then app.window() is called on that.
# The original code does app = Application(backend="uia").connect(...)
# then main_window = app.window(...)
# So, mock_app_class itself is the Application class.
# Its instance (returned by __call__ or connect) should have the window method.
# We need to ensure that the Application constructor itself returns an object
# that then has the connect method.
# And connect itself returns an object that has the window method.
# Revised mocking for Application:
mock_app_instance_for_connect = MagicMock()
mock_app_instance_for_connect.window.return_value = mock_main_window_spec
mock_app_constructor_instance = MagicMock()
mock_app_constructor_instance.connect.return_value = mock_app_instance_for_connect
mock_app_class.return_value = mock_app_constructor_instance
app, window = find_abaqus_window_and_app()
self.assertIsNotNone(app)
self.assertIsNotNone(window)
mock_gw.getWindowsWithTitle.assert_called_with("Abaqus/CAE")
mock_win32process.GetWindowThreadProcessId.assert_called_with(12345)
mock_psutil.Process.assert_called_with(67890)
mock_app_class.assert_called_with(backend="uia")
mock_app_constructor_instance.connect.assert_called_with(handle=12345, timeout=20)
mock_app_instance_for_connect.window.assert_called_with(handle=12345)
self.assertEqual(window, mock_main_window_spec)
@patch('mcp_server.abaqus_app_instance_cache')
@patch('mcp_server.abaqus_main_window_cache')
def test_find_window_cache_hit(self, mock_window_cache, mock_app_cache):
# Setup cache
mock_app_cache.exists.return_value = True # Assuming app cache itself doesn't need exists()
mock_window_cache.exists.return_value = True
mock_window_cache.is_visible.return_value = True
# Need to assign to the module's global directly for the test's context
import mcp_server
mcp_server.abaqus_app_instance_cache = mock_app_cache
mcp_server.abaqus_main_window_cache = mock_window_cache
app, window = find_abaqus_window_and_app()
self.assertEqual(app, mock_app_cache)
self.assertEqual(window, mock_window_cache)
# Reset caches for other tests
mcp_server.abaqus_app_instance_cache = None
mcp_server.abaqus_main_window_cache = None
@patch('mcp_server.gw')
def test_find_window_not_found(self, mock_gw):
mock_gw.getWindowsWithTitle.return_value = []
app, window = find_abaqus_window_and_app()
self.assertIsNone(app)
self.assertIsNone(window)
# Add more tests for find_abaqus_window_and_app (e.g., process name mismatch, connection error)
class TestExecuteScript(unittest.TestCase):
@patch('mcp_server.find_abaqus_window_and_app')
@patch('mcp_server.tempfile.NamedTemporaryFile')
@patch('mcp_server.os.remove')
@patch('mcp_server.time.sleep') # Mock sleep to speed up tests
def test_execute_script_success(self, mock_sleep, mock_os_remove, mock_tempfile, mock_find_abaqus):
# Mock successful Abaqus window and app
mock_app = MagicMock()
mock_main_window = MagicMock()
mock_main_window.exists.return_value = True
mock_main_window.is_minimized.return_value = False
mock_find_abaqus.return_value = (mock_app, mock_main_window)
# Mock temp file creation
mock_tmp_file = MagicMock()
mock_tmp_file.name = "C:\temp\somescript.py" # Use a windows-like path for consistency
mock_tempfile.return_value.__enter__.return_value = mock_tmp_file
# Mock dialog interaction
mock_run_script_dialog = MagicMock()
mock_run_script_dialog.exists.return_value = True
mock_run_script_dialog.window_text.return_value = "Run Script Dialog" # Match one of the conditions
mock_app.top_window.return_value = mock_run_script_dialog # Primary attempt
# If app.active() or main_window.children() were used, they'd need mocking too.
mock_file_name_edit = MagicMock()
mock_file_name_edit.exists.return_value = True
mock_run_script_dialog.child_window.return_value = mock_file_name_edit # Assuming first child_window call gets it
# To be more specific, you could use side_effect if multiple calls are made with different args
mock_ok_button = MagicMock()
mock_ok_button.exists.return_value = True
# Adjust if the second call to child_window is the one for the button
# For simplicity, let's assume child_window with title_re="OK|Run|Open" finds it.
mock_run_script_dialog.child_window.side_effect = [
MagicMock(exists=MagicMock(return_value=True), wrapper_object=MagicMock(return_value=mock_file_name_edit)), # For File &name:
MagicMock(exists=MagicMock(return_value=True), wrapper_object=MagicMock(return_value=mock_ok_button)) # For OK button
]
python_code = "print('Hello Abaqus')"
result = execute_script(python_code)
mock_find_abaqus.assert_called_once()
mock_tempfile.assert_called_once_with(mode="w", suffix=".py", delete=False, encoding='utf-8')
mock_tmp_file.write.assert_called_with(python_code)
mock_main_window.menu_select.assert_called_with("File->Run Script...")
# Check if dialog interactions happened (more specific assertions can be added)
self.assertTrue("File &name:" in str(mock_run_script_dialog.child_window.call_args_list))
self.assertTrue("OK|Run|Open" in str(mock_run_script_dialog.child_window.call_args_list))
mock_file_name_edit_wrapper = mock_run_script_dialog.child_window.side_effect[0].wrapper_object()
mock_file_name_edit_wrapper.set_edit_text.assert_called_with("C:\temp\somescript.py") # Path replacement happens
mock_ok_button_wrapper = mock_run_script_dialog.child_window.side_effect[1].wrapper_object()
mock_ok_button_wrapper.click_input.assert_called_once()
self.assertIn("Script submitted for execution", result)
mock_os_remove.assert_called_with("C:\temp\somescript.py")
@patch('mcp_server.find_abaqus_window_and_app')
def test_execute_script_abaqus_not_found(self, mock_find_abaqus):
mock_find_abaqus.return_value = (None, None)
result = execute_script("print('test')")
self.assertIn("Abaqus/CAE window not found", result)
# Add more tests for execute_script (e.g., dialog not found, control interaction failures)
class TestGetAbaqusMessageLog(unittest.TestCase):
@patch('mcp_server.find_abaqus_window_and_app')
def test_get_log_success_pane_heuristic(self, mock_find_abaqus):
mock_app = MagicMock()
mock_main_window = MagicMock()
mock_main_window.exists.return_value = True
mock_find_abaqus.return_value = (mock_app, mock_main_window)
mock_pane = MagicMock()
mock_pane.is_visible.return_value = True
mock_pane.rectangle.return_value = MagicMock(height=MagicMock(return_value=150), width=MagicMock(return_value=300))
mock_pane.class_name.return_value = "SomeFXWindow"
mock_pane.texts.return_value = [["Line 1", "Line 2"], ["", "Line 3"]] # Simulate texts structure
mock_pane.exists.return_value = True # For the if message_area_control.exists() check
mock_main_window.descendants.return_value = [MagicMock(wrapper_object=MagicMock(return_value=mock_pane))] # descendants returns specs
result = get_abaqus_message_log()
mock_find_abaqus.assert_called_once()
mock_main_window.descendants.assert_any_call(control_type="Pane")
self.assertIn("Line 1\nLine 2\nLine 3", result)
self.assertIn("Message Log Content", result)
@patch('mcp_server.find_abaqus_window_and_app')
def test_get_log_success_edit_heuristic(self, mock_find_abaqus):
mock_app = MagicMock()
mock_main_window = MagicMock()
mock_main_window.exists.return_value = True
mock_find_abaqus.return_value = (mock_app, mock_main_window)
# Pane heuristic fails (no suitable panes)
mock_no_pane = MagicMock()
mock_no_pane.is_visible.return_value = False # Or doesn't match criteria
# Edit heuristic succeeds
mock_edit = MagicMock()
mock_edit.is_visible.return_value = True
mock_edit.is_editable.return_value = False
mock_edit.rectangle.return_value = MagicMock(height=MagicMock(return_value=60), width=MagicMock(return_value=300))
mock_edit.texts.return_value = [["Error: 123", "Warning: 456"]]
mock_edit.exists.return_value = True
mock_main_window.descendants.side_effect = [
[MagicMock(wrapper_object=MagicMock(return_value=mock_no_pane))], # For Pane
[MagicMock(wrapper_object=MagicMock(return_value=mock_edit))] # For Edit
]
result = get_abaqus_message_log()
mock_find_abaqus.assert_called_once()
self.assertIn("Error: 123\nWarning: 456", result)
self.assertIn("Message Log Content", result)
@patch('mcp_server.find_abaqus_window_and_app')
def test_get_log_abaqus_not_found(self, mock_find_abaqus):
mock_find_abaqus.return_value = (None, None)
result = get_abaqus_message_log()
self.assertIn("Abaqus/CAE window not found", result)
@patch('mcp_server.find_abaqus_window_and_app')
def test_get_log_no_message_area_found(self, mock_find_abaqus):
mock_app = MagicMock()
mock_main_window = MagicMock()
mock_main_window.exists.return_value = True
mock_find_abaqus.return_value = (mock_app, mock_main_window)
# Both heuristics fail
mock_main_window.descendants.return_value = [] # No elements found
result = get_abaqus_message_log()
self.assertIn("Message area UI element not found", result)
# Add more tests for get_abaqus_message_log (e.g., control found but no text)
if __name__ == '__main__':
unittest.main(argv=['first-arg-is-ignored'], exit=False)
```
--------------------------------------------------------------------------------
/mcp_server.py:
--------------------------------------------------------------------------------
```python
from mcp.server.fastmcp import FastMCP
import tempfile
import os
import pygetwindow as gw
import win32process
import psutil
from pywinauto import Application, timings, base_wrapper
from pywinauto.controls import uia_controls
import time
from typing import Tuple, Optional
mcp = FastMCP(
"ABAQUS GUI Script Executor",
description="An MCP server to execute Python scripts within an existing Abaqus/CAE GUI session and retrieve message log information. Relies on pywinauto for GUI automation."
)
# Global cache for Abaqus window and app instance
abaqus_main_window_cache: Optional[uia_controls.WindowSpecification] = None
abaqus_app_instance_cache: Optional[Application] = None
def find_abaqus_window_and_app() -> Tuple[Optional[Application], Optional[uia_controls.WindowSpecification]]:
"""
Finds the main Abaqus/CAE window and connects the pywinauto Application object.
It first checks a cache. If not found or invalid, it searches for windows
starting with the title "Abaqus/CAE", verifies the process name,
and then attempts to connect a pywinauto.Application instance to it.
The found application and window objects are cached for subsequent calls.
Relies on `pygetwindow` for initial window discovery and `pywinauto` for connection.
Returns:
Tuple[Optional[Application], Optional[uia_controls.WindowSpecification]]:
A tuple containing the connected `pywinauto.Application` instance and the
main window specification (`WindowSpecification`). Both can be `None` if
the Abaqus/CAE window is not found or connection fails.
"""
global abaqus_main_window_cache, abaqus_app_instance_cache
if abaqus_app_instance_cache and abaqus_main_window_cache and \
abaqus_main_window_cache.exists() and abaqus_main_window_cache.is_visible():
return abaqus_app_instance_cache, abaqus_main_window_cache
abaqus_app_instance_cache = None
abaqus_main_window_cache = None
windows = gw.getWindowsWithTitle("Abaqus/CAE")
found_win_obj = None
for win_ref in windows:
if win_ref.title.startswith("Abaqus/CAE"):
try:
_, pid = win32process.GetWindowThreadProcessId(win_ref._hWnd)
proc = psutil.Process(pid)
if "abaqus" in proc.name().lower() and \
("cae" in proc.name().lower() or "viewer" in proc.name().lower()):
found_win_obj = win_ref
break
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
if found_win_obj:
try:
timings.Timings.slow()
app = Application(backend="uia").connect(handle=found_win_obj._hWnd, timeout=20)
main_window = app.window(handle=found_win_obj._hWnd)
if main_window.exists() and main_window.is_visible():
abaqus_app_instance_cache = app
abaqus_main_window_cache = main_window
return app, main_window
except Exception as e:
print(f"Error connecting to Abaqus window via pywinauto: {e}")
return None, None
@mcp.tool(
name="execute_script_in_abaqus_gui",
description="Executes a Python script in an already running Abaqus/CAE GUI session using the 'File -> Run Script...' menu. Assumes Abaqus/CAE is open and responsive."
)
def execute_script(python_code: str) -> str:
"""
Executes a given Python code string within an active Abaqus/CAE GUI session.
The process involves:
1. Saving the `python_code` to a temporary .py file.
2. Locating the active Abaqus/CAE main window.
3. Automating the GUI to select 'File -> Run Script...' from the menu.
4. Typing the path of the temporary script file into the 'Run Script' dialog.
5. Clicking 'OK' in the dialog to initiate script execution.
6. Deleting the temporary script file after submission.
Args:
python_code (str): The Python script content to be executed, as a string.
Returns:
str: A message indicating the outcome of the script submission attempt.
This primarily confirms if the script was successfully passed to the Abaqus GUI
via the 'Run Script' dialog. It does *not* return the script's own output
or execution status from within Abaqus. The executed script would need to
handle its own output (e.g., writing to files) if results are needed externally.
"""
global abaqus_main_window_cache, abaqus_app_instance_cache
app, main_window = find_abaqus_window_and_app()
if not main_window or not main_window.exists():
abaqus_app_instance_cache = None
abaqus_main_window_cache = None
return "Abaqus/CAE window not found. Please ensure Abaqus/CAE with GUI is running and not minimized initially."
script_file_path: Optional[str] = None
run_script_dialog: Optional[uia_controls.WindowSpecification] = None
try:
with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False, encoding='utf-8') as tmp_script:
tmp_script.write(python_code)
script_file_path = tmp_script.name
script_file_path_for_dialog = script_file_path.replace("/", "\\")
if main_window.is_minimized():
main_window.restore()
main_window.set_focus()
time.sleep(0.5)
main_window.menu_select("File->Run Script...")
time.sleep(1.5) # Wait for Abaqus to open the dialog
dialog_found = False
try:
run_script_dialog = app.top_window() # Primary attempt
if run_script_dialog.exists() and \
("Run Script" in run_script_dialog.window_text() or "Select file" in run_script_dialog.window_text()):
dialog_found = True
if not dialog_found:
time.sleep(1) # Secondary attempt after a slight delay
run_script_dialog = app.active() # Check currently active window of the app
if run_script_dialog.exists() and \
("Run Script" in run_script_dialog.window_text() or "Select file" in run_script_dialog.window_text()):
dialog_found = True
if not dialog_found: # Tertiary attempt: search children of main window
# This is a deeper search if the dialog isn't directly the app's top/active window.
# Useful if the dialog is a child dialog or has an unusual relationship.
possible_dialogs = main_window.children(control_type="Window", top_level_only=False, visible=True)
for diag in possible_dialogs:
if diag.exists() and ("Run Script" in diag.window_text() or "Select file" in diag.window_text()):
run_script_dialog = diag
dialog_found = True
break
if not dialog_found or not run_script_dialog:
raise Exception("'Run Script' dialog not found or title mismatch after menu click.")
except Exception as e_dialog:
print(f"Error finding or identifying the 'Run Script' dialog: {e_dialog}")
return f"Failed to find or identify the 'Run Script' dialog: {e_dialog}"
try:
file_name_edit: Optional[uia_controls.EditWrapper] = None
# Attempt to find by specific title and control type (more reliable)
potential_edit = run_script_dialog.child_window(title="File &name:", control_type="Edit")
if potential_edit.exists(timeout=1):
file_name_edit = potential_edit.wrapper_object()
else:
# Fallback: by control type and index (less reliable, but common)
potential_edit_by_index = run_script_dialog.child_window(control_type="Edit", found_index=0)
if potential_edit_by_index.exists(timeout=1):
file_name_edit = potential_edit_by_index.wrapper_object()
else:
# Fallback: generic Edit control (least reliable for complex dialogs)
generic_edit = run_script_dialog.Edit(found_index=0)
if generic_edit.exists(timeout=1):
file_name_edit = generic_edit
if not file_name_edit:
raise Exception("File name input field (Edit control) not found in 'Run Script' dialog. Searched by title 'File &name:', then by type/index.")
file_name_edit.set_edit_text(script_file_path_for_dialog)
time.sleep(0.3) # Pause after setting text
ok_button: Optional[uia_controls.ButtonWrapper] = None
# Attempt to find by common titles (OK, Run, Open) and control type
potential_button = run_script_dialog.child_window(title_re="OK|Run|Open", control_type="Button")
if potential_button.exists(timeout=1):
ok_button = potential_button.wrapper_object()
else:
# Fallback: by control type and index (less reliable)
potential_button_by_index = run_script_dialog.child_window(control_type="Button", found_index=0)
if potential_button_by_index.exists(timeout=1):
ok_button = potential_button_by_index.wrapper_object()
else:
# Fallback: generic Button control
generic_button = run_script_dialog.Button(found_index=0)
if generic_button.exists(timeout=1):
ok_button = generic_button
if not ok_button:
raise Exception("OK/Run/Open button not found in 'Run Script' dialog. Searched by title regex 'OK|Run|Open', then by type/index.")
ok_button.click_input()
return f"Script submitted for execution via File->Run Script: {script_file_path}"
except Exception as e_interact:
error_detail = str(e_interact)
print(f"Error interacting with 'Run Script' dialog controls: {error_detail}")
if run_script_dialog and run_script_dialog.exists():
try: run_script_dialog.close()
except: pass # Best effort to close
return f"Failed to interact with 'Run Script' dialog (e.g., input script path or click OK): {error_detail}"
except timings.TimeoutError as e_timeout:
abaqus_app_instance_cache = None
abaqus_main_window_cache = None
return f"Timeout occurred during GUI operation: {str(e_timeout)}"
except Exception as e_main:
abaqus_app_instance_cache = None
abaqus_main_window_cache = None
return f"An error occurred during script execution attempt: {str(e_main)}"
finally:
if script_file_path and os.path.exists(script_file_path):
try: os.remove(script_file_path)
except Exception as e_remove:
print(f"Warning: Failed to delete temporary script file {script_file_path}: {e_remove}")
@mcp.tool(
name="get_abaqus_gui_message_log",
description="Attempts to retrieve text from the Abaqus/CAE message/log area. Accuracy depends on UI structure and may require inspect tool information for reliable targeting of the message area control."
)
def get_abaqus_message_log() -> str:
"""
Attempts to retrieve the text content from the Abaqus/CAE message/log area.
This tool relies on GUI automation to find the Abaqus window and then heuristically
searches for a UI element that represents the message/log display. The reliability
of finding this element and extracting its full text can vary significantly based
on the Abaqus version, specific UI configuration, and the complexity of the
message area control (e.g., simple text vs. rich-text vs. custom widget).
For robust operation, providing specific identifiers for the message area UI element
(obtained via an inspect tool like py_inspect or FlaUInspect) is highly recommended.
These identifiers (e.g., AutomationId, Name, ClassName) should be used to replace
the heuristic search logic within this function for your specific Abaqus setup.
Returns:
str: A string containing the extracted text from the message area if found and readable.
If the message area cannot be found or text cannot be extracted, an informative
error or status message is returned.
"""
global abaqus_main_window_cache, abaqus_app_instance_cache
app, main_window = find_abaqus_window_and_app()
if not main_window or not main_window.exists():
abaqus_app_instance_cache = None
abaqus_main_window_cache = None
return "Abaqus/CAE window not found. Cannot retrieve message log."
try:
message_area_control: Optional[base_wrapper.BaseWrapper] = None
# **Highly Recommended: Replace heuristic search below with specific identifiers from an inspect tool.**
# Example using AutomationId (BEST choice if available and static):
# try:
# specific_control = main_window.child_window(automation_id="YourAbaqusMessageAreaAutomationId")
# if specific_control.exists() and specific_control.is_visible():
# message_area_control = specific_control.wrapper_object()
# except Exception as e_specific_find:
# print(f"Failed to find message area by specific AutomationId: {e_specific_find}")
# Heuristic Search (if specific identifiers are not yet configured):
if not message_area_control:
# Heuristic 1: Look for large, visible Panes (often FXWindow in Abaqus for custom areas)
possible_panes = main_window.descendants(control_type="Pane") # More general than just FXWindow initially
for pane_spec in possible_panes:
pane = pane_spec.wrapper_object() # Get the wrapper to access more properties
if pane.is_visible() and pane.rectangle().height > 100 and pane.rectangle().width() > 200:
# Additional check: class_name if it helps narrow down (e.g., "AfxMDIFrame")
# Or if it's known to be an FXWindow that contains text.
if "FXWindow" in pane.class_name(): # Check if it's an FXWindow as they often host content
texts = pane.texts()
if texts and any(line.strip() for group in texts if group for line in group):
message_area_control = pane
break
if message_area_control: print("Message area found via Pane heuristic.")
if not message_area_control:
# Heuristic 2: Look for large, visible, read-only Edit controls
possible_edits = main_window.descendants(control_type="Edit")
for edit_spec in possible_edits:
edit = edit_spec.wrapper_object()
if edit.is_visible() and not edit.is_editable() and edit.rectangle().height > 50:
texts = edit.texts()
if texts and any(line.strip() for group in texts if group for line in group):
message_area_control = edit
break
if message_area_control: print("Message area found via Edit heuristic.")
# Add other specific fallbacks here if more UI details are known, e.g., based on Name or a deeper path.
# Example: specific_control_by_name = main_window.child_window(title="Message Window", control_type="Document")
if message_area_control and message_area_control.exists():
log_content_lines = []
raw_texts = message_area_control.texts() # .texts() often returns list of lists of strings for UIA
for text_group in raw_texts:
if text_group: # Ensure the group itself is not None or empty
for line in text_group:
if line: # Ensure the line string is not None or empty
log_content_lines.append(line)
log_content = "\n".join(log_content_lines).strip()
if not log_content and hasattr(message_area_control, 'window_text'):
log_content = message_area_control.window_text().strip()
if log_content:
return f"Message Log Content (best effort extraction):\n------------------------\n{log_content}\n------------------------"
else:
return ("Found a potential message area UI element, but could not extract text content. "
"The control might be custom, empty, or text extraction method failed. More specific inspect details are needed.")
else:
return ("Message area UI element not found using current heuristics. "
"For reliable message log retrieval, please use an inspect tool to identify the specific properties "
"(e.g., AutomationId, Name, ClassName) of the Abaqus message area and update this function's search logic.")
except Exception as e:
abaqus_app_instance_cache = None
abaqus_main_window_cache = None
return f"An error occurred while trying to retrieve the Abaqus message log: {str(e)}"
@mcp.prompt()
def abaqus_scripting_strategy() -> str:
"""
Defines the preferred strategy for interacting with an Abaqus/CAE GUI session
using this MCP server. This prompt guides an LLM agent on how to effectively
use the available tools for scripting and information retrieval.
"""
return """When performing tasks in an Abaqus/CAE GUI session via this MCP server:
1. **Core Assumption:** This server interacts with an ALREADY RUNNING Abaqus/CAE GUI session. It does not start or stop Abaqus/CAE. Ensure the Abaqus/CAE application is open, responsive, and ideally the primary focused window when initiating tool calls.
2. **Executing Python Scripts (`execute_script_in_abaqus_gui` tool):
* **Purpose:** Use this tool to run custom Python scripts within the Abaqus/CAE environment.
* **Input:** Provide the complete Python script as a string to the `python_code` argument. This script should contain valid Abaqus Scripting Interface (ASI) commands. Ensure the script is self-contained or that any required models/files are already loaded or accessible within the Abaqus session as the script would expect.
* **Mechanism:** This tool automates the 'File -> Run Script...' menu selection and dialog interaction in the Abaqus GUI.
* **Return Value:** The tool returns a string message indicating that the script was *submitted* to the Abaqus GUI. It does NOT return the direct output (e.g., print statements from your script) or catch Python exceptions raised *within* the Abaqus script's execution context.
* **Idempotency:** This tool is not idempotent. Calling it multiple times with the same script will execute the script multiple times in Abaqus.
* **Checking Script Outcome:** After submitting a script, it is CRUCIAL to use the `get_abaqus_gui_message_log` tool to check the Abaqus message area. This is where you will find:
* Confirmation of script completion (often specific messages printed by Abaqus itself).
* Any `print()` statements from your Python script.
* Error messages or warnings generated by Abaqus or your script if it failed or encountered issues.
3. **Retrieving Abaqus GUI Messages (`get_abaqus_gui_message_log` tool):
* **Purpose:** Use this tool to fetch the text content from the Abaqus/CAE message/log area (often at the bottom of the main window).
* **Primary Use Cases:**
* To verify the outcome of scripts run via `execute_script_in_abaqus_gui`.
* To check for general Abaqus status messages, warnings, or errors that may have occurred during manual or scripted operations.
* **Reliability Note:** This tool attempts to scrape text from a GUI element. Its accuracy can depend on the specific Abaqus version and UI configuration. The current implementation uses heuristics to find the message area. If it fails to retrieve the log accurately or completely, the server's GUI interaction logic for this tool might need adjustment based on specific UI element identifiers (e.g., AutomationId, Name, ClassName) obtained from an inspect tool for your Abaqus environment.
4. **Recommended Workflow for Script Execution & Verification:**
a. Ensure the Abaqus/CAE GUI is running, visible, and in a stable state (e.g., no blocking modal dialogs other than those expected by the tools).
b. Formulate the Abaqus Python script (ASI commands) you want to run.
c. Call `execute_script_in_abaqus_gui` with your script string.
d. Note the confirmation message (script submitted).
e. Wait a reasonable amount of time for the script to likely execute within Abaqus. This duration depends heavily on the script's complexity and the operations it performs.
f. Call `get_abaqus_gui_message_log`.
g. Carefully examine the returned string from `get_abaqus_gui_message_log` to understand the actual outcome of your script, including any errors or messages it printed.
5. **Troubleshooting GUI Interaction and Best Practices:**
* **Window State:** Ensure the Abaqus/CAE window is not minimized when initiating actions. The tools attempt to restore and focus, but an already active window is best.
* **Modal Dialogs:** Avoid having unexpected modal dialogs open in Abaqus, as they can block the GUI automation tools.
* **Tool Failures:** If `execute_script_in_abaqus_gui` fails (e.g., cannot find dialogs/controls), it might indicate an unexpected Abaqus state, a change in UI structure, or the Abaqus window being unresponsive. The `get_abaqus_gui_message_log` (if it can run) might offer clues. Otherwise, manual inspection of the Abaqus GUI will be necessary.
* **Script Errors vs. Tool Errors:** Differentiate between errors returned by the MCP tools (e.g., "dialog not found") and errors that appear in the Abaqus message log (which are errors from your script's execution within Abaqus).
"""
if __name__ == "__main__":
mcp.run()
```