diff --git a/.github/workflows/ci_cd.yml b/.github/workflows/ci_cd.yml index 864b8327..8af1ff64 100644 --- a/.github/workflows/ci_cd.yml +++ b/.github/workflows/ci_cd.yml @@ -29,19 +29,22 @@ jobs: token: ${{ secrets.GITHUB_TOKEN }} tests: - name: "Tests" - runs-on: windows-latest + # Preserve the Windows check names required by existing branch protection. + name: ${{ matrix.os == 'windows-latest' && format('Tests ({0})', matrix.python-version) || format('Tests ({0}, {1})', matrix.os, matrix.python-version) }} + runs-on: ${{ matrix.os }} strategy: matrix: + os: [windows-latest, ubuntu-22.04, ubuntu-24.04] python-version: ['3.10', '3.11', '3.12', '3.13', '3.14'] fail-fast: false env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} DISPLAY: ':99' + QT_QPA_PLATFORM: offscreen steps: - name: Install Linux os dependencies if: runner.os == 'Linux' - run: sudo apt install libegl1 + run: sudo apt-get update && sudo apt-get install -y libegl1 libgl1 libopengl0 libxkbcommon0 - name: Setup headless display uses: pyvista/setup-headless-display-action@v5 @@ -61,6 +64,20 @@ jobs: python-version: ${{ env.MAIN_PYTHON_VERSION }} dependencies: "libegl1" + mcp-linux-distros: + name: "MCP Qt integration - ${{ matrix.distro }}" + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + distro: ["quay.io/centos/centos:stream9", "fedora:40"] + steps: + - uses: actions/checkout@v7 + - name: Build the supported distro test environment + run: docker build --build-arg DISTRO=${{ matrix.distro }} -f scripts/mcp-validation.Dockerfile -t apm-mcp-test . + - name: Exercise Qt, offline installation, profiles and server processes + run: docker run --rm apm-mcp-test + doc-deploy: name: "Deploy development documentation" runs-on: ubuntu-latest @@ -251,6 +268,9 @@ jobs: - name: Update and Install development tools - Fedora if: contains(matrix.os, 'fedora') run: | + # Fedora 40 is retained as a packaging target and uses archived repositories. + sed -i 's|^metalink=|#metalink=|; s|^#baseurl=http://download.example/pub/fedora/linux/|baseurl=https://archives.fedoraproject.org/pub/archive/fedora/linux/|' \ + /etc/yum.repos.d/fedora.repo /etc/yum.repos.d/fedora-updates.repo yum update -y yum group install development-tools -y diff --git a/README.rst b/README.rst index 1b91b8dc..ea6d1af4 100644 --- a/README.rst +++ b/README.rst @@ -28,6 +28,10 @@ Ansys Python Manager (QT) This is a simple cross-platform `QT `_ application you can use to install Python and (optional) PyAnsys packages. +The **PyAnsys MCPs** tab also installs and manages the public PyAnsys MCP +servers, their isolated environments, HTTP processes, and coding-agent profiles. +See the `MCP management guide `_. + .. image:: images/app-image.png :align: center :alt: Screenshot of Python Installer application diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index c85afc13..d6024927 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -6,14 +6,13 @@ Contributing Any code contributions are welcome and it is the developer team's hope that this guide facilitates an understanding of the ``ansys-tools-installer`` code repository. It is important to note that while the ``ansys-tools-installer`` software -package is maintained by ANSYS and any submissions are reviewed -thoroughly before merging, we still seek to foster a community that can -support user questions and develop new features to make this software -a useful tool for all users. As such, we welcome and encourage any -questions or submissions to this repository. +package is maintained by ANSYS and submissions are reviewed +thoroughly before merging, community members can help answer questions +and develop features that make this software useful to all users. +Questions and submissions to this repository are welcome. For contributing to this project, please refer to the `PyAnsys Developer's Guide`_. .. include:: ../../README.rst - :start-after: .. contribute_start \ No newline at end of file + :start-after: .. contribute_start diff --git a/doc/source/index.rst b/doc/source/index.rst index b176293d..d4403854 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst @@ -12,4 +12,5 @@ installer contributing - user_guide \ No newline at end of file + user_guide + mcp diff --git a/doc/source/installer.rst b/doc/source/installer.rst index 723053b4..2243aabd 100644 --- a/doc/source/installer.rst +++ b/doc/source/installer.rst @@ -8,7 +8,7 @@ Installing the ``Ansys Python Manager`` .. tab-item:: Windows - First step is installing the ``Ansys Python Manager``. In order to do so, follow the next steps. + To install the ``Ansys Python Manager``, follow these steps. #. Download the necessary installer from the `latest available release `_. The file should be named ``Ansys-Python-Manager-Setup-v*.exe``. @@ -119,7 +119,7 @@ Installing the ``Ansys Python Manager`` Under **WSL (Windows Subsystem for Linux)**, you can install the lighter ``xterm`` instead of ``gnome-terminal``. ``mesa-libGL``, ``mesa-libEGL``, - and ``xcb-util-cursor`` are still required to display the application. + and ``xcb-util-cursor`` are still required to display the app. #. Install **zlib** package using **wget** @@ -169,7 +169,7 @@ Installing the ``Ansys Python Manager`` #. Click ``Uninstall`` button. - #. Follow the uninstaller script & provide sudo permission to uninstall the application. + #. Follow the uninstaller script & provide sudo permission to uninstall the app. .. tab-item:: Fedora39 @@ -190,7 +190,7 @@ Installing the ``Ansys Python Manager`` Under **WSL (Windows Subsystem for Linux)**, you can install the lighter ``xterm`` instead of ``gnome-terminal``. ``mesa-libGL``, ``mesa-libEGL``, - and ``xcb-util-cursor`` are still required to display the application. + and ``xcb-util-cursor`` are still required to display the app. #. Install **zlib** package using **wget** @@ -240,7 +240,7 @@ Installing the ``Ansys Python Manager`` #. Click ``Uninstall`` button. - #. Follow the uninstaller script & provide sudo permission to uninstall the application. + #. Follow the uninstaller script & provide sudo permission to uninstall the app. Installing Python @@ -248,11 +248,11 @@ Installing Python Now, instructions on how to install Python from the ``Ansys Python Manager`` are provided. -In order to do so, just follow the upcoming steps: +To do so, follow these steps: #. Search for the ``Ansys Python Manager`` and run it. -#. Go to the ``Install Python`` tab, and select your desired Python install, version and extra packages. +#. Go to the ``Install Python`` tab, and select your desired Python install, version, and extra packages. #. And follow the install process. @@ -277,26 +277,26 @@ Regarding the available Python versions, users can select among the following on 1. Conda python installation: - #. Bash scripts will be downloaded and executed on a machine directly from the official website.(https://github.com/conda-forge/miniforge?tab=readme-ov-file). + #. The installer downloads and executes Bash scripts directly from the official website (https://github.com/conda-forge/miniforge). 2. Standard python installation happens in two ways: - #. If the Debian version is 22.04 and Python 3.11 (recommended by Ansys) is specified, the installer will - automatically install the pre-compiled version of Python available within the installer. + #. If the Debian version is 22.04 and Python 3.11 (recommended by Ansys) is specified, the installer + automatically installs the pre-compiled version of Python available within the installer. - #. Otherwise, Python will be installed following these steps: + #. Otherwise, the installer follows these steps: - #. Download Python Tarball and Untar: + #. Download and extract the Python archive: - i. The Python tar file will be downloaded from the Python FTP server (https://www.python.org/ftp/python) - based on the version selected from the dropdown menu. Example: For Python version 3.12.0, the download link + i. The installer downloads the Python archive from the Python FTP server (https://www.python.org/ftp/python) + based on the version selected from the dropdown menu. For example, for Python version 3.12.0, the download link would be here(https://www.python.org/ftp/python/3.12.0/Python-3.12.0.tar.xz). ii. Decompress the downloaded file in the user’s cache directory. * Configure the Source: - i. Following will be executed configure the installation: + i. Run the following command to configure the installation: .. code:: shell diff --git a/doc/source/mcp.rst b/doc/source/mcp.rst new file mode 100644 index 00000000..9eb3d6cf --- /dev/null +++ b/doc/source/mcp.rst @@ -0,0 +1,266 @@ +Manage PyAnsys MCPs +=================== + +The **PyAnsys MCPs** tab installs the public Ansys Model Context Protocol +(MCP) servers and configures coding agents to use them. Each product has a +separate Python environment, so installing one server does not change another +server's dependencies. The manager itself continues to support Python 3.10 +and later; the MCP environments need newer Python versions. + +Supported servers +----------------- + +.. list-table:: Product launch contracts + :header-rows: 1 + :widths: 22 28 22 28 + + * - Product + - Package + - Python baseline + - Transports + * - `PyAEDT MCP `_ + - ``ansys-aedt-mcp`` + - 3.13–3.14 + - Stdio, HTTP + * - `PyMechanical MCP `_ + - ``ansys-mechanical-mcp`` + - 3.12–3.14 + - Stdio, HTTP + * - `PyFluent MCP `_ + - ``ansys-fluent-mcp`` + - 3.12+ + - Stdio, HTTP + * - `PyMAPDL MCP `_ + - ``ansys-mapdl-mcp`` + - 3.12–3.14 + - Stdio, HTTP + * - `PyLumerical MCP `_ + - ``ansys-lumerical-mcp`` + - 3.11+ + - Stdio + * - `PyCFX MCP `_ + - ``ansys-cfx-mcp`` + - 3.12–3.14 + - Stdio, HTTP + +These ranges follow the official installation guides and package declarations. +Before installation, the manager checks the exact release's ``Requires-Python`` +metadata against the selected interpreter and the documented product range. +Git installations read ``requires-python`` from the selected branch or tag; +offline installations read the selected wheel's metadata. For example, +PyLumerical 0.1.0 supports Python 3.11, while current development requires +Python 3.12. Pip also validates the requirements of all dependencies. +``ansys-common-mcp`` is a framework dependency installed by the product +packages, rather than a separate solver server in the catalog. + +Ansys products and appropriate licenses must be installed or accessible +separately. Consult each server's setup guide for supported solver versions, +platforms, and local or remote connection requirements. Installing an MCP +package does not install or license an Ansys solver. + +Install a server +---------------- + +#. Install a compatible 64-bit Python using **Install Python**, or use an + existing installation. Python 3.13 is a useful common baseline. +#. Select a product in **PyAnsys MCPs**, then open **Installation**. +#. Under **Python environment**, keep **Dedicated environment (recommended)** + and use **Select Python version**, the same dropdown used by + **Create virtual environments**. The selector remains available after installation. + Selecting another Python creates or reuses a separate dedicated environment; + the previous environment is preserved. +#. To reuse a virtual or conda environment, choose **Existing virtual environment**. + **Available virtual environments** uses the same discovery as + **Manage Python environments**. System Python installations are rejected as + installation targets. Stop the manager's server before changing its environment. +#. Select a PyPI release (leave **Latest** to check the newest published release), + or an official Git branch, tag, or commit. Git installations require Git. +#. Click **Install MCP**. For an installed MCP, the action becomes **Update / repair**. + Progress appears below the page; expand **Activity log** for details. + The final installation step checks dependency consistency. + +Managed environments and settings are under +``~/.ansys/ansys_python_manager/mcp``. Managed environments also appear in +**Manage Python environments**. Cancelling an installation can leave a +partial environment; retry **Update / repair** to finish it. A cancelled or +failed installation is never reported as successful. + +**Latest** checks PyPI every time and installs that exact version with upgrade +enabled, including when an older version is already installed. It never +substitutes an older MCP release to accommodate an unsupported Python. If the +version check cannot reach PyPI, installation stops without changing the +environment. Choose an explicit version from the dropdown for reproducible setups; the +version field cannot be edited. Opening it loads releases automatically. APM caches this list for +15 minutes; **Latest** still performs a fresh check before installation. + +The Python dropdowns update for the selected product, source, and release. +APM checks the actual interpreter version and architecture against the exact +release requirements. Unsupported discovered Python versions are hidden from the normal dropdown. +Virtual environments remain visible with compatibility information. A compatible Python is selected for a new dedicated environment; +an existing environment is never silently replaced by another selection. +Late responses from an earlier selection cannot change the current choices. +Installation always checks the requirements again before making changes. + +Returning to this tab reuses the choices already discovered by the other APM +tabs. **Refresh** scans in the background without blocking navigation. Use +**Other locations and details** to add a Python executable or an environment +outside the configured search folders, or to inspect the full environment path. +Manually added Python interpreters remain visible even outside the documented +product range. For those explicit selections, the release's own ``Requires-Python`` +metadata and the 64-bit requirement still apply. APM never silently replaces +an explicit interpreter with another Python. A release that requires Python +3.12 cannot be installed on Python 3.9 through this option. + +Existing incompatible environments are preserved; create a supported +environment in **Create virtual environments** and select it here. + +On Linux, uninstalling the manager offers separate options to remove settings +and managed environments. Removing settings preserves MCP environments; +removing managed environments includes the product environments. Existing +custom environments outside the manager's configured locations are preserved. + +For an offline installation, select **Offline wheelhouse** under **Install from** +and provide a directory of +wheels or a wheelhouse ZIP. Include the chosen MCP package and all dependencies, +including build dependencies if distributing source packages. Wheels must +match the target operating system, architecture, and Python version. The +manager passes ``--no-index`` to pip and does not query PyPI. +Git sources are unavailable in offline mode. ZIP extraction +rejects traversal paths and symbolic links. +The version dropdown automatically lists versions found in the selected folder +or ZIP. In offline mode, **Latest** means the newest stable MCP wheel in the selected +wheelhouse; the manager does not contact PyPI. + +Connect a coding agent +---------------------- + +For one local coding agent, use **stdio**. The agent starts the installed +MCP console script directly. The manager does not need to remain open. +For shared HTTP access, use **Start HTTP server** under **Server settings**. +The manager binds to ``127.0.0.1`` and waits for an MCP initialize response +before reporting readiness. Its servers stop when the manager exits. + +The **Local HTTP server** section separates the endpoint and server status from +the optional **Solver connection** section. Solver host and port appear only +when connecting on startup is enabled. Less common options are under +**Advanced launch settings**, with separate sections for product options, +additional arguments, and environment variables. Server actions stay visible +when scrolling or viewing the activity log. PyLumerical instead shows its +automatic stdio connection and a shortcut to **Coding agents**. + +HTTP transport ports are distinct from Ansys solver connection ports. +PyAEDT, PyMechanical, and PyMAPDL expose solver connection fields. PyAEDT also +offers graphical mode, context tools, and dynamic tool discovery. Additional +product options are read from the installed release when expanding advanced +settings. Use **Add an option** to select a flag, a choice, or a value. Options +include their help text and defaults in tooltips. APM reads the argument parser +in a separate process and exits before starting a server or connecting a solver. +Unsupported saved options must be removed before launching. If a future release +changes its parser, consult **Documentation** and use **Custom arguments**. +Expert options can also be entered as a JSON string array, for example: + +.. code-block:: json + + ["--transport-mode", "mtls", "--certs-dir", "C:/Ansys certificates"] + +Environment overrides are a JSON object of string names and values. They are +passed to manager-owned HTTP processes and included in stdio client profiles. +Settings, profiles and backups store these values as plain text. + +Under **Coding agents**, select VS Code, the Copilot command-line tool, Claude Desktop, +Cursor, Codex, or OpenCode. Review the destination path. VS Code defaults to +the current Copilot harness and its personal ``~/.copilot/mcp-config.json``, +respecting ``COPILOT_HOME``. **Choose workspace** selects a project +``.mcp.json`` instead. For older installations, choose **Local harness (legacy)** +to use the VS Code user-profile ``mcp.json`` or a workspace ``.vscode/mcp.json``. +The current format uses ``mcpServers``; the legacy format uses ``servers``. +See the `VS Code MCP configuration reference `_. +Choose **Automatic (stdio)** for an agent-managed process or **Shared HTTP server** +for an already running server. Claude Desktop's local +configuration supports stdio here; PyLumerical offers stdio only. + +Click **Review configuration**, review the complete merged document, then click +**Save reviewed configuration**. The same button guides both steps; editing +any connection setting requires a new review. The review section opens when a preview is available; +the actions stay visible below the page. The manager preserves unrelated entries, +backs up existing files, and replaces the destination atomically. Existing +product entries are updated under their current names, including recognized +aliases such as ``pymechanical`` and ``pymechanical-mcp``. Matching aliases +are consolidated, and repeated saves do not add duplicate servers. Tool +restrictions, timeouts, unrelated environment variables, and other preferences +are retained. If several custom entries launch the same product, APM refuses +to guess which one to replace. It refuses +to overwrite a file changed after preview. Codex TOML comments are preserved. +JSON files must be strict JSON: files containing comments or duplicate keys +are rejected without modification. Merge the preview manually when a client +uses JSON with comments. Reload or restart the coding agent after saving. +Codex profiles include a 60-second startup timeout for MCP imports on a cold +environment. The command and argument fields follow the +`official Codex MCP configuration `_. + +New OpenCode profiles follow the current V2 ``mcp.servers`` layout. Existing +V1 files with server entries directly under ``mcp`` keep their layout; mixed +V1/V2 files require manual migration. These formats follow the +`OpenCode MCP reference `_. + +The generated profiles reference the selected environment. Regenerate them +after changing the environment or connection settings. An HTTP profile uses +the selected HTTP port; start that server before connecting the client. + +Architecture and validation +--------------------------- + +The existing ``main`` module composes the Python installation, environment +creation and package-management tabs. ``find_python`` discovers registry, +Ansys, conda, and configured virtual environments. Platform-specific installers +and terminal launchers remain in ``windows_functions`` and ``linux_functions``. +``configure_json`` owns the existing environment search settings; updates and +PyInstaller/NSIS/Linux packaging remain independent of MCP package installation. + +The MCP integration uses a separate native PySide6 tab. The +`PyAEDT desktop app `_ +informed its installation, server controls, advanced settings, logs, and +profile workflows. Its Flet UI, Windows embedded runtime, tray integration, +and product-specific executable detection are not dependencies of this Qt app. + +``mcp_catalog`` defines package and command-line differences. ``mcp_backend`` handles +installation plans, metadata, settings, and wheelhouses. ``mcp_process`` owns +asynchronous subprocesses and HTTP readiness. ``mcp_owned_process`` contains +their descendants in Windows jobs or Unix process sessions, so persistent +Python workers stop with the server. ``mcp_profiles`` merges client +configurations, and ``mcp_tab`` connects these services to Qt. Adding a product +requires verifying its published package, Python requirements, launch command, +transports and client interoperability before extending the catalog and tests. +``mcp_launch`` reads installed launch options without starting a server. +``mcp_releases`` resolves exact releases and validates interpreter versions +against their metadata before installation. + +The command contracts were cross-checked against the official +`PyAEDT `_, +`PyMechanical `_, +`PyFluent `_, +`PyMAPDL `_, +`PyLumerical `_, +and `PyCFX `_ +guides. Stable documentation can lag a release: for example, Fluent 0.9 installs +its solver backend as a dependency, although the older stable installation +guide still lists a separate extra. Published package metadata determines the +actual installation requirements. + +The automated suite exercises installation using a small offline wheel, +profile preservation, product-specific arguments, settings, real subprocesses, +cancellation, and protocol readiness. CI runs on Windows and Ubuntu 22.04/24.04, +with container tests on CentOS Stream 9 and Fedora 40. Reproduce the latter with +``scripts/mcp-validation.Dockerfile``. + +For opt-in testing against published packages, run: + +.. code-block:: console + + python scripts/validate_mcp.py --python /path/to/python3.13 --root /tmp/apm-mcp + +This installs the selected products through the Qt installation pipeline, +performs stdio initialization and tool discovery, and checks HTTP initialization +where supported. It writes ``validation.json`` beneath the validation root. +It does not exercise solver execution or licensing; those checks require +the corresponding product installations and licenses. diff --git a/doc/source/user_guide.rst b/doc/source/user_guide.rst index b3f0dc22..179e15fc 100644 --- a/doc/source/user_guide.rst +++ b/doc/source/user_guide.rst @@ -110,13 +110,13 @@ environment with the available IDEs and development environments. For example, you can launch the Spyder IDE by selecting the virtual environment from the available list and clicking on the ``Launch Spyder`` option. Likewise, you can launch the Jupyter Notebook, -Jupyter Lab and console. +Jupyter Lab, and console. .. image:: _static/launch_options.PNG :align: center :alt: Screenshot of Launch Options -**Tip:** By using ``Launch console`` option, you can launch the +You can use the ``Launch console`` option to launch the virtual environment in the command prompt and subsequently navigate to the development folder and launch the VS Code IDEs using command line option “``code .``” And set the interpreter to the virtual @@ -199,4 +199,4 @@ References - `Ansys Python Manager GitHub Repository `__ - `Ansys Python Manager - Documentation `__ \ No newline at end of file + Documentation `__ diff --git a/doc/styles/config/vocabularies/ANSYS/accept.txt b/doc/styles/config/vocabularies/ANSYS/accept.txt index 4e86b28e..089cb315 100644 --- a/doc/styles/config/vocabularies/ANSYS/accept.txt +++ b/doc/styles/config/vocabularies/ANSYS/accept.txt @@ -11,3 +11,10 @@ Spyder Synopsys synopsys Windows +MCPs +conda +Flet +subprocesses +zlib +coreutils +Pythonic diff --git a/pyproject.toml b/pyproject.toml index e00fe78a..736ce1fd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,8 +15,9 @@ dependencies = [ "PyGithub", "appdirs", "requests", - "PySide6", + "PySide6>=6.7", "ansys-tools-common", + "tomlkit>=0.13,<1", "setuptools; python_version >= '3.12'", ] classifiers = [ @@ -36,6 +37,7 @@ dynamic = ["version"] [project.optional-dependencies] tests = [ + "tomlkit==0.13.3", "packaging==26.3", "PyGithub==2.10.0", "appdirs==1.4.4", @@ -55,6 +57,7 @@ doc = [ "sphinx_toolbox==4.3.1", ] freeze = [ + "tomlkit==0.13.3", "pyinstaller==6.22.3", "packaging==26.3", "PyGithub==2.10.0", diff --git a/scripts/mcp-validation.Dockerfile b/scripts/mcp-validation.Dockerfile new file mode 100644 index 00000000..af00ff34 --- /dev/null +++ b/scripts/mcp-validation.Dockerfile @@ -0,0 +1,28 @@ +# Reproduce the MCP Qt/offline-install tests on the Linux packaging targets. +# docker build --build-arg DISTRO=ubuntu:22.04 -f scripts/mcp-validation.Dockerfile -t apm-mcp-test . +# docker run --rm apm-mcp-test +ARG DISTRO=ubuntu:24.04 +FROM ghcr.io/astral-sh/uv:0.10.4 AS uv +FROM ${DISTRO} +COPY --from=uv /uv /usr/local/bin/uv +RUN if [ -f /etc/fedora-release ] && grep -q 'release 40 ' /etc/fedora-release; then \ + sed -i 's|^metalink=|#metalink=|; s|^#baseurl=http://download.example/pub/fedora/linux/|baseurl=https://archives.fedoraproject.org/pub/archive/fedora/linux/|' \ + /etc/yum.repos.d/fedora.repo /etc/yum.repos.d/fedora-updates.repo; \ + fi +RUN if command -v apt-get >/dev/null; then \ + apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates libegl1 libopengl0 libxkbcommon0 libdbus-1-3 \ + libfontconfig1 libglib2.0-0 libxrender1 libxext6 libx11-6; \ + else \ + dnf install -y ca-certificates mesa-libEGL mesa-libGL libxkbcommon \ + dbus-libs fontconfig glib2 libXrender libXext libX11; \ + fi +RUN if command -v apt-get >/dev/null; then apt-get install -y --no-install-recommends libgl1; fi +WORKDIR /workspace +COPY pyproject.toml README.rst LICENSE ./ +COPY src ./src +COPY tests ./tests +COPY scripts/validate_mcp.py ./scripts/validate_mcp.py +ENV QT_QPA_PLATFORM=offscreen UV_LINK_MODE=copy +RUN uv venv --python 3.13 /opt/apm && uv pip install --python /opt/apm/bin/python -e '.[tests]' +CMD ["/opt/apm/bin/python", "-m", "pytest", "tests/test_mcp_backend.py", "tests/test_mcp_releases.py", "tests/test_mcp_compatibility.py", "tests/test_mcp_profiles.py", "tests/test_mcp_process.py", "tests/test_mcp_launch.py", "tests/test_mcp_tab.py", "-q", "--tb=short"] diff --git a/scripts/validate_mcp.py b/scripts/validate_mcp.py new file mode 100644 index 00000000..c71444e7 --- /dev/null +++ b/scripts/validate_mcp.py @@ -0,0 +1,210 @@ +"""Opt-in live MCP validation; installs packages but does not launch Ansys solvers. + +Run with the manager's development Python. Example:: + + python scripts/validate_mcp.py --python /path/to/python3.13 --root /tmp/apm-mcp + +This exercises the real Qt installation pipeline, stdio initialize/tools/list, +and HTTP readiness. It writes a machine-readable report beneath the given root. +""" + +import argparse +import json +from pathlib import Path +import queue +import socket +import subprocess +import threading +import time + +from PySide6 import QtWidgets + +from ansys.tools.installer.mcp_backend import ( + console_executable, + installed_version, +) +from ansys.tools.installer.mcp_catalog import PRODUCTS +from ansys.tools.installer.mcp_tab import McpTab + + +def stdio_probe(executable, arguments, timeout=90): + """Initialize a real server and list its tools without calling solver tools.""" + messages = queue.Queue() + errors = [] + process = subprocess.Popen( + [str(executable), *arguments], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + encoding="utf-8", + errors="replace", + ) + + def read_output(): + for line in process.stdout: + try: + messages.put(json.loads(line)) + except ValueError: + errors.append(line) + + def read_errors(): + for line in process.stderr: + errors.append(line) + + readers = [ + threading.Thread(target=read_output, daemon=True), + threading.Thread(target=read_errors, daemon=True), + ] + for reader in readers: + reader.start() + + def send(message): + process.stdin.write(json.dumps({"jsonrpc": "2.0", **message}) + "\n") + process.stdin.flush() + + def response(identifier): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if process.poll() is not None: + raise RuntimeError( + f"Server exited {process.returncode}: {''.join(errors)[-8000:]}" + ) + try: + message = messages.get(timeout=0.2) + except queue.Empty: + continue + if message.get("id") == identifier: + if "error" in message: + raise RuntimeError(str(message["error"])) + return message["result"] + raise TimeoutError(f"MCP response timed out: {''.join(errors)[-8000:]}") + + try: + send( + { + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-03-26", + "capabilities": {}, + "clientInfo": {"name": "apm-validation", "version": "1"}, + }, + } + ) + initialized = response(1) + send({"method": "notifications/initialized"}) + send({"id": 2, "method": "tools/list", "params": {}}) + tools = response(2)["tools"] + if not tools: + raise RuntimeError("Server returned no tools.") + return {"server": initialized["serverInfo"], "tools": len(tools)} + finally: + process.stdin.close() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + for reader in readers: + reader.join(timeout=2) + process.stdout.close() + process.stderr.close() + + +def main(): + """Run the requested products through installation and protocol validation.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--python", required=True, help="64-bit Python 3.13 executable") + parser.add_argument("--root", required=True, type=Path) + parser.add_argument( + "--products", nargs="*", choices=[product.key for product in PRODUCTS] + ) + parser.add_argument("--skip-install", action="store_true") + args = parser.parse_args() + app = QtWidgets.QApplication([]) + tab = McpTab(directory=args.root.absolute()) + report = {} + try: + for index, product in enumerate(PRODUCTS): + if args.products and product.key not in args.products: + continue + tab.product_select.setCurrentIndex(index) + result = {} + report[product.key] = result + print(f"Validating {product.name}…", flush=True) + try: + if not args.skip_install: + tab.select_python(args.python) + tab._install(False) + deadline = time.monotonic() + 1500 + while tab.queue.active or tab._preparing: + app.processEvents() + if time.monotonic() > deadline: + tab.queue.shutdown() + raise TimeoutError("Installation timed out.") + time.sleep(0.01) + if "completed" not in tab.status.text(): + raise RuntimeError( + tab.status.text() + "\n" + tab.log.toPlainText()[-12000:] + ) + result["version"] = installed_version(tab.environment, product) + tab._load_launch_options() + deadline = time.monotonic() + 60 + while tab._launch_context != tab._launch_signature(): + app.processEvents() + if time.monotonic() > deadline: + raise RuntimeError(tab.launch_hint.text()) + time.sleep(0.01) + result["launch_options"] = [ + option["flags"][0] for option in tab._launch_schema + ] + command = console_executable(tab.environment, product) + result["stdio"] = stdio_probe(command, tab._arguments("stdio")) + if product.http_flags: + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + port = probe.getsockname()[1] + tab.http_port.setValue(port) + tab._start_server() + server = tab.servers[product.key] + deadline = time.monotonic() + 70 + while ( + server.active + and not server.state.startswith("Ready:") + and time.monotonic() < deadline + ): + app.processEvents() + time.sleep(0.01) + if not server.state.startswith("Ready:"): + raise RuntimeError( + server.state + "\n" + tab.log.toPlainText()[-10000:] + ) + result["http"] = "initialize passed" + server.shutdown() + else: + result["http"] = "unsupported by product launcher" + result["passed"] = True + print(json.dumps(result), flush=True) + except Exception as error: + result["passed"] = False + result["error"] = str(error) + print(str(error), flush=True) + finally: + args.root.mkdir(parents=True, exist_ok=True) + (args.root / "validation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8" + ) + finally: + tab.shutdown() + return ( + 0 if report and all(result.get("passed") for result in report.values()) else 1 + ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/ansys/tools/installer/find_python.py b/src/ansys/tools/installer/find_python.py index 3c96be7b..defda308 100644 --- a/src/ansys/tools/installer/find_python.py +++ b/src/ansys/tools/installer/find_python.py @@ -35,6 +35,7 @@ find_miniforge_linux, is_linux_os, ) +from ansys.tools.installer.mcp_backend import application_directory # only used on windows try: @@ -143,7 +144,10 @@ def _find_installed_ansys_python_win(): if os.path.exists(path): try: version_output = subprocess.check_output( - [f"{path}\\python.exe", "--version"], text=True + [f"{path}\\python.exe", "--version"], + text=True, + creationflags=subprocess.CREATE_NO_WINDOW, + timeout=10, ).strip() version = version_output.split()[1] paths[path] = (version, False) @@ -175,7 +179,7 @@ def _find_installed_python_linux(): LOG.debug("Identifying all installed versions of python on Linux") pythons = {} - version_names = ["python", "python3"] + [f"python3.{i}" for i in range(7, 13)] + version_names = ["python", "python3"] + [f"python3.{i}" for i in range(7, 15)] previous_found_version = "" for version_name in version_names: @@ -249,7 +253,11 @@ def get_all_python_venv(): paths = {} script_path = "bin" if is_linux_os() else "Scripts" configure = ConfigureJson() - for venv_dir in configure.venv_search_path: + search_paths = [ + *configure.venv_search_path, + str(application_directory() / "environments"), + ] + for venv_dir in dict.fromkeys(search_paths): try: for venv_dir_name in os.listdir(venv_dir): if os.path.isfile( diff --git a/src/ansys/tools/installer/installed_table.py b/src/ansys/tools/installer/installed_table.py index 81c0d3d4..9711786c 100644 --- a/src/ansys/tools/installer/installed_table.py +++ b/src/ansys/tools/installer/installed_table.py @@ -68,17 +68,28 @@ def __init__( installed_python=False, installed_forge=False, created_venv=False, + populate_on_init=True, ): """Initialize the dropdown by populating it.""" super().__init__(parent) + # Keep long installation paths from forcing the entire window wider. + # The full path remains available in each item's tooltip. + self.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon) + self.setMinimumContentsLength(24) + self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) + self.installed_python = installed_python self.installed_forge = installed_forge self.created_venv = created_venv + self.destroyed.connect(self.stop) self._destroyed = False self._locked = True - self.populate() + if populate_on_init: + self.populate() + else: + self._locked = False self.signal_update.connect(self.populate) def update(self, timeout=1.0): @@ -97,59 +108,44 @@ def update(self, timeout=1.0): def populate(self): """Populate the dropdown.""" - self._locked = True - self.clear() + self.set_entries(self.discover()) - if self._destroyed: - return - - # Check for python & conda forge versions + def discover(self): + """Collect entries without accessing Qt, allowing background discovery.""" + entries = [] + groups = [] if self.installed_python or self.installed_forge: - LOG.debug("Populating the dropdown with python and conda forge versions.") - python_lst = find_all_python() - conda_lst = find_miniforge() - - for path, (version, admin) in python_lst.items(): - admin_badge = " [admin]" if admin else "" - label = f"Python {version}{admin_badge} — {path}" - self.addItem(label) - idx = self.count() - 1 - self.setItemData( - idx, - {"version": f"Python {version}", "admin": str(admin), "path": path}, - ) - self.setItemData(idx, path, QtCore.Qt.ItemDataRole.ToolTipRole) - - for path, (version, admin) in conda_lst.items(): - admin_badge = " [admin]" if admin else "" - label = f"Conda {version}{admin_badge} — {path}" - self.addItem(label) - idx = self.count() - 1 - self.setItemData( - idx, - {"version": f"Conda {version}", "admin": str(admin), "path": path}, - ) - self.setItemData(idx, path, QtCore.Qt.ItemDataRole.ToolTipRole) - + groups = [("Python", find_all_python()), ("Conda", find_miniforge())] elif self.created_venv: - LOG.debug("Populating the dropdown with virtual environments.") - venv_lst = get_all_python_venv() - if not venv_lst: - self.addItem("None") - self.setItemData( - 0, {"version": "None", "admin": "None", "path": "None"} - ) - else: - for path, (version, admin) in venv_lst.items(): - label = f"{version} — {path}" - self.addItem(label) - idx = self.count() - 1 - self.setItemData( - idx, {"version": version, "admin": str(admin), "path": path} + groups = [("", get_all_python_venv())] + for prefix, inventory in groups: + for path, (version, admin) in inventory.items(): + name = f"{prefix} {version}" if prefix else version + badge = " [admin]" if admin else "" + entries.append( + ( + f"{name}{badge} — {path}", + { + "version": name, + "admin": str(admin), + "path": path, + }, ) - self.setItemData(idx, path, QtCore.Qt.ItemDataRole.ToolTipRole) + ) + if self.created_venv and not entries: + entries.append( + ("None", {"version": "None", "admin": "None", "path": "None"}) + ) + return entries - self.destroyed.connect(self.stop) + def set_entries(self, entries): + """Apply a discovery snapshot on the GUI thread.""" + if self._destroyed: + return + self.clear() + for label, data in entries: + self.addItem(label, data) + self.setItemData(self.count() - 1, data["path"], QtCore.Qt.ToolTipRole) self._locked = False def stop(self): @@ -582,6 +578,17 @@ def delete_virtual_environment(self, point): "venv_table" ) + if ( + action == delete_action + and self._parent is not None + and hasattr(self._parent, "mcp_tab") + and self._parent.mcp_tab.environment_in_use(parent_path) + ): + self._parent.show_error( + "Stop the MCP server and wait for installation to finish before deleting its environment." + ) + return + if is_vanilla_python and action == delete_action: try: # Delete the python virtual environment @@ -623,6 +630,26 @@ def _run_linux_or_report_error(self, func, *args, **kwargs): if self._parent is not None and hasattr(self._parent, "show_error"): self._parent.show_error(str(err)) + def _mcp_operation_blocks_changes(self): + """Protect MCP environments from concurrent package changes in this tab.""" + if self._parent is None or not hasattr(self._parent, "mcp_tab"): + return False + table = self.table if self.is_chk_box_active() else self.venv_table + selected = table.active_path + if not selected or selected == "None": + return False + root = ( + os.path.dirname(selected) + if os.path.basename(selected) in ("Scripts", "bin") + else selected + ) + if self._parent.mcp_tab.environment_in_use(root): + self._parent.show_error( + "Stop the MCP server and wait for installation to finish before changing packages in its environment." + ) + return True + return False + def launch_cmd( self, extra: str = "", @@ -640,6 +667,12 @@ def launch_cmd( always_use_pip : bool, default: False Whether to always use pip for the command or not. """ + if ( + isinstance(extra, str) + and "pip install" in extra + and self._mcp_operation_blocks_changes() + ): + return path = os.environ["PATH"].split(";") altered_path = path.copy() for p in path: diff --git a/src/ansys/tools/installer/main.py b/src/ansys/tools/installer/main.py index 26695fde..fea7e1fd 100644 --- a/src/ansys/tools/installer/main.py +++ b/src/ansys/tools/installer/main.py @@ -60,6 +60,7 @@ query_gh_latest_release_linux, update_app, ) +from ansys.tools.installer.mcp_tab import McpTab from ansys.tools.installer.misc import ImageWidget, PyAnsysDocsBox, enable_logging from ansys.tools.installer.progress_bar import ProgressBar from ansys.tools.installer.uninstall import Uninstall @@ -80,7 +81,7 @@ def __init__(self, show=True): """Instantiate Ansys Python Manager main class.""" super().__init__() self.setWindowTitle("Ansys Python Manager") - self.setGeometry(50, 50, 500, 780) # width should auto-update + self.setGeometry(50, 50, 800, 780) self._exceptions = [] self._pbar = None @@ -179,6 +180,8 @@ def __init__(self, show=True): self.venv_table_tab = CreateVenvTab(self) self.tab_widget.addTab(self.venv_table_tab, "Create virtual environments") self.tab_widget.addTab(self.installed_table_tab, "Manage Python environments") + self.mcp_tab = McpTab(self) + self.tab_widget.addTab(self.mcp_tab, "PyAnsys MCPs") # Create the layout for the container container_layout = QtWidgets.QVBoxLayout() @@ -289,6 +292,11 @@ def __init__(self, show=True): if show: self.show() + def closeEvent(self, event): + """Reap MCP subprocesses when the manager window is closed.""" + self.mcp_tab.shutdown() + super().closeEvent(event) + @protected def _exe_update(self, filename): """After downloading the update for this application, run the file and shutdown this application.""" diff --git a/src/ansys/tools/installer/mcp_backend.py b/src/ansys/tools/installer/mcp_backend.py new file mode 100644 index 00000000..052a745a --- /dev/null +++ b/src/ansys/tools/installer/mcp_backend.py @@ -0,0 +1,460 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Installation plans and persistent settings independent of the Qt UI.""" + +from dataclasses import dataclass, replace +from email.parser import Parser +import json +import os +from pathlib import Path +import re +import tempfile +import zipfile + +from packaging.version import Version +import requests + +from ansys.tools.installer.mcp_releases import ( + PythonInfo, + ReleaseInfo, + compatible_python, + inspect_python, + published_release, + source_release, + validate_python, + wheelhouse_release, +) + + +def application_directory(): + """Return the manager's per-user MCP configuration directory.""" + return Path.home() / ".ansys" / "ansys_python_manager" / "mcp" + + +def atomic_write(path, content): + """Replace a text file atomically, using private permissions for new files.""" + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + if path.exists(): + os.chmod(temporary, path.stat().st_mode & 0o777) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + +def read_settings(path): + """Read saved settings, refusing to silently replace a damaged file.""" + if not Path(path).exists(): + return {} + data = json.loads(Path(path).read_text(encoding="utf-8")) + if not isinstance(data, dict) or any( + not isinstance(value, dict) for value in data.values() + ): + raise ValueError(f"Invalid MCP settings: {path}") + return data + + +def python_executable(directory, windows=None): + """Find Python in a virtual environment, conda environment or scripts folder.""" + root = Path(directory).expanduser().absolute() + if root.is_file(): + return root + windows = os.name == "nt" if windows is None else windows + candidates = ( + [root / "Scripts" / "python.exe", root / "python.exe"] + if windows + else [root / "bin" / "python", root / "python", root / "python3"] + ) + for candidate in candidates: + if candidate.is_file(): + return candidate + return candidates[0] + + +def console_executable(directory, product, windows=None): + """Return the installed console script without resolving venv symlinks.""" + windows = os.name == "nt" if windows is None else windows + root = Path(directory).expanduser().absolute() + return ( + root + / ("Scripts" if windows else "bin") + / (product.package + (".exe" if windows else "")) + ) + + +def managed_environment(directory, product, base_python): + """Reuse a matching legacy venv or isolate a different base interpreter.""" + root = Path(directory) / "environments" / product.key + selected = str(Path(base_python).expanduser().absolute()) if base_python else "" + + def origin(executable): + seen = set() + while ( + executable + and executable not in seen + and Path(executable).parent.name.lower() in ("scripts", "bin") + ): + seen.add(executable) + executable = ( + environment_base_python(Path(executable).parent.parent) or executable + ) + # Resolve only for identity comparison; launch commands retain the + # original venv path so its environment is never bypassed. + return str(Path(executable).resolve()) if executable else "" + + selected = origin(selected) + original = environment_base_python(root) + original = origin(original) + if ( + not python_executable(root).is_file() + or not selected + or not original + or os.path.normcase(original) == os.path.normcase(selected) + ): + return root + import hashlib + + identity = hashlib.sha256(os.path.normcase(selected).encode("utf-8")).hexdigest()[ + :12 + ] + return root.with_name(f"{product.key}-{identity}") + + +def environment_base_python(directory): + """Read a venv's creator without running an interpreter or changing files.""" + config = Path(directory) / "pyvenv.cfg" + try: + text = config.read_text(encoding="utf-8") + except (OSError, UnicodeError): + return "" + values = dict(line.split("=", 1) for line in text.splitlines() if "=" in line) + values = {key.strip().lower(): value.strip() for key, value in values.items()} + executable = values.get("executable") + if not executable and values.get("home"): + executable = str( + Path(values["home"]) / ("python.exe" if os.name == "nt" else "python") + ) + return str(Path(executable).expanduser().absolute()) if executable else "" + + +def installed_version(directory, product): + """Read distribution metadata without importing the MCP or its solver.""" + root = Path(directory) + paths = [root / "Lib" / "site-packages"] + paths.extend(root.glob("lib*/python*/site-packages")) + name = product.package.replace("-", "_") + for site in paths: + for metadata in site.glob(f"{name}-*.dist-info/METADATA"): + message = Parser().parsestr(metadata.read_text(encoding="utf-8")) + if message.get("Version"): + return message["Version"] + return None + + +def package_requirement(product, source="release", version="", branch="main"): + """Build one pip requirement using only an official product repository.""" + if source == "branch": + if not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_./-]*", branch): + raise ValueError( + "Enter a Git branch, tag or commit without URL characters." + ) + return f"{product.package} @ git+{product.repository}.git@{branch}" + if source != "release": + raise ValueError("Unknown installation source.") + return f"{product.package}=={Version(version)}" if version else product.package + + +def prepare_wheelhouse(source, destination): + """Use a wheel directory or safely extract a wheelhouse ZIP without links.""" + source = Path(source).expanduser() + if source.is_dir(): + return source.absolute() + if not source.is_file() or source.suffix.lower() != ".zip": + raise ValueError("Select a wheelhouse directory or ZIP file.") + destination = Path(destination) + with zipfile.ZipFile(source) as archive: + for member in archive.infolist(): + target = (destination / member.filename).resolve() + if ( + not target.is_relative_to(destination.resolve()) + or "\\" in member.filename + or (member.external_attr >> 16) & 0o170000 == 0o120000 + ): + raise ValueError("Wheelhouse contains an unsafe archive path.") + archive.extractall(destination) + return destination + + +def installation_commands( + product, + directory, + base_python, + requirement, + *, + custom=False, + offline=None, + upgrade=False, + release=None, + interpreter=None, +): + """Plan validated installation into a dedicated environment using its Python.""" + root = Path(directory).expanduser().absolute() + python = python_executable(root) + is_environment = (root / "pyvenv.cfg").is_file() or (root / "conda-meta").is_dir() + if custom and (not is_environment or not python.is_file()): + raise ValueError( + "Choose an existing virtual or conda environment, not a system Python." + ) + if not custom and root.exists() and not is_environment: + raise ValueError( + f"Refusing to reuse a directory that is not an environment: {root}" + ) + probe_python = python if python.is_file() else Path(base_python).expanduser() + if not probe_python.is_file(): + raise ValueError( + "Select a compatible Python executable from the Create environments tab or Browse." + ) + if offline and "git+" in requirement: + raise ValueError("Offline installation supports releases, not Git branches.") + release = release or ReleaseInfo("selected release", product.python, requirement) + interpreter = validate_python( + interpreter or inspect_python(probe_python), product, release + ) + expected = Version(interpreter.version).release[:3] + # Detect interpreter changes after preflight without requiring packaging in + # the target environment. Full PEP 440 validation runs in the manager above. + probe = ( + "import sys,struct; " + f"assert sys.version_info[:3] == {expected!r}, " + "'The Python interpreter changed after validation; retry installation'; " + "assert struct.calcsize('P') == 8, 'A 64-bit Python is required'" + ) + commands = [[str(probe_python), "-I", "-c", probe]] + if not python.is_file(): + commands.append([str(probe_python), "-I", "-m", "venv", str(root)]) + commands.append( + [ + str(python), + "-I", + "-c", + "import importlib.util,runpy; " + "runpy.run_module('ensurepip',run_name='__main__') " + "if importlib.util.find_spec('pip') is None else None", + ] + ) + command = [str(python), "-I", "-m", "pip", "--disable-pip-version-check", "install"] + if upgrade or requirement == product.package: + command.append("--upgrade") + if offline: + command.extend(["--no-index", "--find-links", str(offline)]) + command.append(requirement) + commands.append(command) + commands.append([str(python), "-I", "-m", "pip", "check"]) + return commands + + +@dataclass(frozen=True) +class InstallationPlan: + """Hold a resolved release and the commands validated for its interpreter.""" + + release: ReleaseInfo + interpreter: PythonInfo + commands: list[list[str]] + creating_environment: bool + + +def _installed_pythons(): + # Import lazily: discovery also uses this module's configuration path. + from ansys.tools.installer.find_python import find_all_python, find_miniforge + + discovered = find_all_python() + discovered.update(find_miniforge()) + entries = sorted( + discovered.items(), + key=lambda item: (str(item[1][0]).startswith("3.13"), str(item[1][0])), + reverse=True, + ) + return [str(python_executable(path)) for path, _metadata in entries] + + +def prepare_installation( + product, + directory, + base_python, + *, + version="", + source="release", + branch="main", + custom=False, + wheelhouse=None, + extract_to=None, + upgrade=False, + allow_fallback=True, + enforce_catalog_python=True, +): + """Resolve the requested release and supported Python before mutating an environment.""" + release, offline = resolve_release( + product, + version=version, + source=source, + branch=branch, + wheelhouse=wheelhouse, + extract_to=extract_to, + ) + validation_product = ( + product if enforce_catalog_python else replace(product, python="") + ) + root = Path(directory).expanduser().absolute() + existing = python_executable(root) + creating = not existing.is_file() + if not creating: + try: + interpreter = validate_python( + inspect_python(existing), validation_product, release + ) + except ValueError as error: + raise ValueError( + f"{error}\nThis existing environment was preserved. Create a supported " + "environment in Create virtual environments and select it here." + ) from error + elif custom: + raise ValueError( + "Choose an existing virtual or conda environment, not a system Python." + ) + else: + try: + interpreter = compatible_python(validation_product, release, base_python) + except ValueError: + if not allow_fallback: + raise + interpreter = compatible_python( + validation_product, release, base_python, _installed_pythons() + ) + commands = installation_commands( + validation_product, + root, + interpreter.executable, + release.requirement, + custom=custom, + offline=offline, + upgrade=upgrade or (source == "release" and not version), + release=release, + interpreter=interpreter, + ) + return InstallationPlan(release, interpreter, commands, creating) + + +def resolve_release( + product, + *, + version="", + source="release", + branch="main", + wheelhouse=None, + extract_to=None, +): + """Resolve the same exact release for selector checks and installation.""" + requirement = package_requirement(product, source, version, branch) + offline = prepare_wheelhouse(wheelhouse, extract_to) if wheelhouse else None + if offline: + if source == "branch": + raise ValueError( + "Offline installation supports releases, not Git branches." + ) + release = wheelhouse_release(product, offline, version) + elif source == "branch": + release = source_release(product, branch, requirement) + else: + release = published_release(product, version) + return release, offline + + +def available_versions(product, wheelhouse=None): + """Fetch non-yanked stable versions with a bounded, verified HTTPS request.""" + if wheelhouse is not None: + from packaging.utils import canonicalize_name, parse_wheel_filename + + path = Path(wheelhouse) + if path.is_dir(): + names = [p.name for p in path.glob("*.whl")] + else: + with zipfile.ZipFile(path) as archive: + names = archive.namelist() + versions = set() + for name in names: + if not name.endswith(".whl"): + continue + try: + package, version, _build, _tags = parse_wheel_filename(Path(name).name) + except ValueError: + continue + if ( + package == canonicalize_name(product.package) + and not version.is_prerelease + ): + versions.add(version) + return [str(version) for version in sorted(versions, reverse=True)] + response = requests.get(f"https://pypi.org/pypi/{product.package}/json", timeout=20) + response.raise_for_status() + return sorted( + [ + version + for version, files in response.json()["releases"].items() + if files + and any(not file.get("yanked") for file in files) + and not Version(version).is_prerelease + ], + key=Version, + reverse=True, + ) + + +def server_arguments(product, transport="stdio", port=8080, extra=()): + """Build product-specific CLI arguments, keeping transport flags unambiguous.""" + if transport not in ("stdio", "http"): + raise ValueError("Unknown MCP transport.") + reserved = {"--transport", "--http-host", "--http-port"} + if product.http_flags == ("--host", "--port"): + reserved.update(product.http_flags) + if any(argument.split("=", 1)[0] in reserved for argument in extra): + raise ValueError( + "Set HTTP/stdio transport and HTTP port in the connection controls." + ) + if product.http_flags is None: + if transport != "stdio": + raise ValueError(f"{product.name} currently supports stdio only.") + return list(extra) + arguments = ["--transport", transport] + if transport == "http": + if not 1 <= port <= 65535: + raise ValueError("HTTP port must be between 1 and 65535.") + host_flag, port_flag = product.http_flags + arguments.extend([host_flag, "127.0.0.1", port_flag, str(port)]) + return [*arguments, *extra] diff --git a/src/ansys/tools/installer/mcp_catalog.py b/src/ansys/tools/installer/mcp_catalog.py new file mode 100644 index 00000000..66663ea2 --- /dev/null +++ b/src/ansys/tools/installer/mcp_catalog.py @@ -0,0 +1,113 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Verified product contracts for the public PyAnsys MCP servers. + +Keep CLI differences here rather than assuming all servers share the common MCP +launcher. See the repository links and ``doc/source/mcp.rst`` before updating. +""" + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class McpProduct: + """Describe a product's package, launcher and supported transports.""" + + key: str + name: str + package: str + python: str + description: str + http_flags: tuple[str, str] | None = ("--http-host", "--http-port") + connect_flag: str = "" + machine_flag: str = "--ip" + product_port: int = 0 + + @property + def repository(self): + """Return the official source repository.""" + return f"https://github.com/ansys/{self.key}-mcp" + + @property + def documentation(self): + """Return the official installation guide used to verify this contract.""" + product = self.package.removeprefix("ansys-").removesuffix("-mcp") + return f"https://{product}-mcp.docs.pyansys.com/version/stable/getting_started/installation.html" + + +PRODUCTS = ( + McpProduct( + "pyaedt", + "PyAEDT MCP", + "ansys-aedt-mcp", + ">=3.13,<3.15", + "Electronics Desktop: HFSS, Maxwell, Icepak, Q3D and circuit workflows.", + connect_flag="--connect", + machine_flag="--machine", + product_port=50051, + ), + McpProduct( + "pymechanical", + "PyMechanical MCP", + "ansys-mechanical-mcp", + ">=3.12,<3.15", + "Mechanical: remote sessions, models, analyses, scripts and results.", + connect_flag="--connect-on-startup", + product_port=10000, + ), + McpProduct( + "pyfluent", + "PyFluent MCP", + "ansys-fluent-mcp", + ">=3.12,<4", + "Fluent: CFD solver sessions, setup, execution and post-processing.", + http_flags=("--host", "--port"), + ), + McpProduct( + "pymapdl", + "PyMAPDL MCP", + "ansys-mapdl-mcp", + ">=3.12,<3.15", + "Mechanical APDL: sessions, modeling, solving, files and results.", + connect_flag="--connect-on-startup", + product_port=50052, + ), + McpProduct( + "pylumerical", + "PyLumerical MCP", + "ansys-lumerical-mcp", + ">=3.11,<4", + "Lumerical: FDTD, MODE, DEVICE and INTERCONNECT sessions. Stdio only.", + http_flags=None, + ), + McpProduct( + "pycfx", + "PyCFX MCP", + "ansys-cfx-mcp", + ">=3.12,<3.15", + "CFX: solver sessions and CFD simulation workflows.", + http_flags=("--host", "--port"), + ), +) + +PRODUCT_BY_KEY = {product.key: product for product in PRODUCTS} diff --git a/src/ansys/tools/installer/mcp_compatibility.py b/src/ansys/tools/installer/mcp_compatibility.py new file mode 100644 index 00000000..4d1ee0af --- /dev/null +++ b/src/ansys/tools/installer/mcp_compatibility.py @@ -0,0 +1,87 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Read release requirements and inspect APM's discovered Python environments.""" + +from dataclasses import dataclass +from pathlib import Path +import tempfile + +from ansys.tools.installer.mcp_backend import resolve_release +from ansys.tools.installer.mcp_releases import ( + PythonInfo, + ReleaseInfo, + inspect_python, + validate_python, +) + + +@dataclass(frozen=True) +class Compatibility: + """Hold a release and the supported/unsupported interpreter choices.""" + + release: ReleaseInfo + interpreters: dict[str, PythonInfo] + errors: dict[str, str] + probes: dict + + +def check_compatibility( + product, + paths, + *, + version="", + source="release", + branch="main", + wheelhouse=None, + probes=None, +): + """Check selected release metadata and actual interpreters without mutations.""" + with tempfile.TemporaryDirectory(prefix="apm-mcp-check-") as temporary: + release, _offline = resolve_release( + product, + version=version, + source=source, + branch=branch, + wheelhouse=wheelhouse, + extract_to=temporary, + ) + supported, errors = {}, {} + cache = dict(probes or {}) + for executable in dict.fromkeys(paths): + if not executable: + continue + try: + path = Path(executable) + stat = path.stat() + stamp = (stat.st_mtime_ns, stat.st_size, stat.st_ino) + previous = cache.get(executable) + info = ( + previous[1] + if previous and previous[0] == stamp + else inspect_python(executable) + ) + cache[executable] = (stamp, info) + supported[executable] = validate_python(info, product, release) + except Exception as error: + errors[executable] = str(error) + return Compatibility(release, supported, errors, cache) diff --git a/src/ansys/tools/installer/mcp_launch.py b/src/ansys/tools/installer/mcp_launch.py new file mode 100644 index 00000000..a4e235b2 --- /dev/null +++ b/src/ansys/tools/installer/mcp_launch.py @@ -0,0 +1,132 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Read launch options from the installed MCP's parser without starting a server.""" + +import json +import os +import subprocess + +from ansys.tools.installer.mcp_backend import python_executable + +# Intercept parsing before any launcher can create its server or connect a solver. +# Run in the target environment: APM never imports a solver package itself. +_INSPECT = r""" +import argparse, contextlib, importlib.metadata, io, json, sys +class Captured(BaseException): pass +def capture(parser, *args, **kwargs): + options = [] + for action in parser._actions: + flags = [f for f in action.option_strings if f.startswith('--')] + if not flags or isinstance(action, (argparse._HelpAction, argparse._VersionAction)): + continue + if action.help == argparse.SUPPRESS: + continue + kind = 'flag' if action.nargs == 0 else 'value' + options.append(dict(flags=flags, kind=kind, nargs=action.nargs, + choices=list(action.choices) if action.choices is not None else None, + type=getattr(action.type, '__name__', 'str'), help=action.help or '', + default=action.default if isinstance(action.default, (str,int,float,bool,list,type(None))) else None)) + sys.__stdout__.write('APM_OPTIONS=' + json.dumps(options) + '\n') + raise Captured() +argparse.ArgumentParser.parse_args = capture +argparse.ArgumentParser.parse_known_args = capture +package, command = sys.argv[1:3] +sys.argv = [command, '--help'] +try: + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + distribution = importlib.metadata.distribution(package) + entry = next(e for e in distribution.entry_points if e.group == 'console_scripts' and e.name == command) + entry.load()() +except Captured: + pass +else: + raise RuntimeError('The launcher did not expose an argparse parser.') +""" + + +def launch_options(environment, product): + """Return parser metadata for this installed release, using a hidden subprocess.""" + if product.key == "pylumerical": + return [] # Its FastMCP entry point does not parse command-line arguments. + process = subprocess.run( + [ + str(python_executable(environment)), + "-I", + "-c", + _INSPECT, + product.package, + product.package, + ], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=45, + creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0, + ) + for line in process.stdout.splitlines(): + if line.startswith("APM_OPTIONS="): + return json.loads(line.removeprefix("APM_OPTIONS=")) + raise ValueError( + "This release's launch options could not be read. See its documentation." + ) + + +def option_arguments(options, values): + """Validate selected values against the installed parser and serialize argv.""" + schema = {option["flags"][0]: option for option in options} + arguments = [] + for flag, value in values.items(): + if flag not in schema: + raise ValueError(f"{flag} is not supported by this installed MCP release.") + option = schema[flag] + if option["kind"] == "flag": + if value is not True: + raise ValueError(f"{flag} must be enabled or removed.") + arguments.append(flag) + continue + values_list = value if isinstance(value, list) else [value] + nargs = option["nargs"] + if ( + nargs in (None, "?") + and len(values_list) != 1 + or nargs == "+" + and not values_list + or type(nargs) is int + and len(values_list) != nargs + ): + raise ValueError(f"Incorrect number of values for {flag}.") + for entry in values_list: + if not isinstance(entry, str) or not entry or "\0" in entry: + raise ValueError(f"Enter a value for {flag}.") + if option["choices"] is not None and entry not in map( + str, option["choices"] + ): + raise ValueError(f"Unsupported value for {flag}.") + if option["type"] in ("int", "validate_port", "_validate_port"): + try: + int(entry) + except ValueError as error: + raise ValueError(f"{flag} requires a whole number.") from error + arguments.extend([flag, *values_list]) + return arguments diff --git a/src/ansys/tools/installer/mcp_owned_process.py b/src/ansys/tools/installer/mcp_owned_process.py new file mode 100644 index 00000000..0a860ffe --- /dev/null +++ b/src/ansys/tools/installer/mcp_owned_process.py @@ -0,0 +1,151 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Contain manager-owned workers in a Windows job or Unix process session.""" + +import os +import signal + +from PySide6 import QtCore + + +def _windows_job(pid): + """Assign a process to a private kill-on-close job, returning its handle.""" + import ctypes + from ctypes import wintypes + + class BasicLimits(ctypes.Structure): + _fields_ = [ + ("process_time", ctypes.c_longlong), + ("job_time", ctypes.c_longlong), + ("flags", wintypes.DWORD), + ("minimum_working_set", ctypes.c_size_t), + ("maximum_working_set", ctypes.c_size_t), + ("active_processes", wintypes.DWORD), + ("affinity", ctypes.c_size_t), + ("priority", wintypes.DWORD), + ("scheduling", wintypes.DWORD), + ] + + class ExtendedLimits(ctypes.Structure): + _fields_ = [ + ("basic", BasicLimits), + ("io_counters", ctypes.c_ulonglong * 6), + ("process_memory", ctypes.c_size_t), + ("job_memory", ctypes.c_size_t), + ("peak_process_memory", ctypes.c_size_t), + ("peak_job_memory", ctypes.c_size_t), + ] + + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + kernel.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR] + kernel.CreateJobObjectW.restype = wintypes.HANDLE + kernel.SetInformationJobObject.argtypes = [ + wintypes.HANDLE, + ctypes.c_int, + ctypes.c_void_p, + wintypes.DWORD, + ] + kernel.SetInformationJobObject.restype = wintypes.BOOL + kernel.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] + kernel.OpenProcess.restype = wintypes.HANDLE + kernel.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE] + kernel.AssignProcessToJobObject.restype = wintypes.BOOL + kernel.CloseHandle.argtypes = [wintypes.HANDLE] + kernel.CloseHandle.restype = wintypes.BOOL + job = kernel.CreateJobObjectW(None, None) + if not job: + raise ctypes.WinError(ctypes.get_last_error()) + process = None + try: + limits = ExtendedLimits() + limits.basic.flags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + if not kernel.SetInformationJobObject( + job, 9, ctypes.byref(limits), ctypes.sizeof(limits) + ): + raise ctypes.WinError(ctypes.get_last_error()) + process = kernel.OpenProcess(0x0101, False, pid) # SET_QUOTA | TERMINATE + if not process or not kernel.AssignProcessToJobObject(job, process): + raise ctypes.WinError(ctypes.get_last_error()) + return kernel, job + except OSError: + kernel.CloseHandle(job) + raise + finally: + if process: + kernel.CloseHandle(process) + + +class OwnedProcess(QtCore.QProcess): + """Stop descendant processes together with the owned top-level process.""" + + def __init__(self, parent=None): + """Configure containment before the first process is launched.""" + super().__init__(parent) + self._job = None + self._group = None + self.ownership_error = "" + if os.name != "nt": + self.setUnixProcessParameters( + QtCore.QProcess.UnixProcessFlag.CreateNewSession + ) + self.started.connect(self._attach) + self.finished.connect(self._release) + + def _attach(self): + self.ownership_error = "" + try: + if os.name == "nt": + self._job = _windows_job(self.processId()) + else: + self._group = self.processId() + except OSError as error: + self.ownership_error = f"Could not contain the MCP process tree: {error}" + super().kill() + + def _release(self, *_): + if self._job is not None: + kernel, handle = self._job + self._job = None + kernel.CloseHandle(handle) + if self._group is not None: + group = self._group + self._group = None + try: + os.killpg(group, signal.SIGKILL) + except ProcessLookupError: + pass + + def terminate(self): + """Request termination of the private process session on Unix.""" + if self._group is not None: + try: + os.killpg(self._group, signal.SIGTERM) + except ProcessLookupError: + pass + else: + super().terminate() + + def kill(self): + """Kill all contained descendants, including persistent Python workers.""" + self._release() + super().kill() diff --git a/src/ansys/tools/installer/mcp_process.py b/src/ansys/tools/installer/mcp_process.py new file mode 100644 index 00000000..c75fcae0 --- /dev/null +++ b/src/ansys/tools/installer/mcp_process.py @@ -0,0 +1,342 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Asynchronous, owned subprocesses for installation and HTTP MCP servers.""" + +import codecs +import json +import socket +import time + +from PySide6 import QtCore, QtNetwork + +from ansys.tools.installer.mcp_owned_process import OwnedProcess + + +def process_environment(overrides=None): + """Keep the user environment while removing frozen Python startup variables.""" + environment = QtCore.QProcessEnvironment.systemEnvironment() + for key in ("PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV"): + environment.remove(key) + environment.insert("PYTHONUNBUFFERED", "1") + environment.insert("PYTHONIOENCODING", "utf-8") + for key, value in (overrides or {}).items(): + environment.insert(key, value) + return environment + + +class CommandQueue(QtCore.QObject): + """Run an installation plan without blocking the GUI or invoking a shell.""" + + output = QtCore.Signal(str) + completed = QtCore.Signal(bool, str) + + def __init__(self, parent=None): + """Create one reusable process and its timeout watchdog.""" + super().__init__(parent) + self.process = OwnedProcess(self) + self.process.setProcessChannelMode(QtCore.QProcess.MergedChannels) + self.process.setProcessEnvironment(process_environment()) + self.process.readyReadStandardOutput.connect(self._read) + self.process.finished.connect(self._finished) + self.process.errorOccurred.connect(self._error) + self.timer = QtCore.QTimer(self) + self.timer.setSingleShot(True) + self.timer.timeout.connect(self._timeout) + self.kill_timer = QtCore.QTimer(self) + self.kill_timer.setSingleShot(True) + self.kill_timer.timeout.connect(self._kill_if_needed) + self.active = False + self.commands = [] + self.failure = "" + self._decoder = codecs.getincrementaldecoder("utf-8")("replace") + + def start(self, commands): + """Start a new command plan, rejecting overlapping installations.""" + if self.active: + raise RuntimeError("An MCP operation is already in progress.") + if not commands: + raise ValueError("An installation plan must contain commands.") + self.commands = list(commands) + self.active = True + self.failure = "" + self._next() + + def _next(self): + self.kill_timer.stop() + if not self.commands: + self._complete(True, "Installation completed and dependencies checked.") + return + command = self.commands.pop(0) + self._decoder = codecs.getincrementaldecoder("utf-8")("replace") + self.output.emit(f"\n> {command[0]} {' '.join(command[1:])}\n") + self.process.start(command[0], command[1:]) + self.timer.start(20 * 60 * 1000) + + def _read(self): + self.output.emit( + self._decoder.decode(bytes(self.process.readAllStandardOutput())) + ) + + def _finished(self, code, status): + self.timer.stop() + self.kill_timer.stop() + self._read() + self.output.emit(self._decoder.decode(b"", final=True)) + if not self.active: + return + if self.failure or code or status != QtCore.QProcess.NormalExit: + self._complete( + False, + self.failure + or self.process.ownership_error + or f"Command failed (exit {code}). See the log.", + ) + else: + self._next() + + def _error(self, error): + if error == QtCore.QProcess.FailedToStart: + self._complete(False, self.process.errorString()) + + def _complete(self, success, message): + if not self.active: + return + self.timer.stop() + self.kill_timer.stop() + self.active = False + self.commands = [] + self.completed.emit(success, message) + + def cancel( + self, message="Installation cancelled. Retry to repair a partial environment." + ): + """Terminate the owned command and discard the remaining plan.""" + if not self.active: + return + self.failure = message + self.commands = [] + self.process.terminate() + self.kill_timer.start(2000) + + @QtCore.Slot() + def _timeout(self): + self.cancel("Command timed out.") + + def _kill_if_needed(self): + if self.failure and self.process.state() != QtCore.QProcess.NotRunning: + self.process.kill() + + def shutdown(self): + """Reap the command before its QObject owner is destroyed.""" + if self.active: + self.cancel() + if not self.process.waitForFinished(2000): + self.process.kill() + self.process.waitForFinished(2000) + + +class McpServer(QtCore.QObject): + """Own an HTTP server and report readiness after an MCP initialize response.""" + + output = QtCore.Signal(str) + changed = QtCore.Signal(str) + + def __init__(self, parent=None): + """Initialize the server process and bounded readiness polling.""" + super().__init__(parent) + self.process = OwnedProcess(self) + self.process.setProcessChannelMode(QtCore.QProcess.MergedChannels) + self.process.readyReadStandardOutput.connect(self._read) + self.process.finished.connect(self._finished) + self.process.errorOccurred.connect(self._error) + self.network = QtNetwork.QNetworkAccessManager(self) + self.network.setProxy(QtNetwork.QNetworkProxy(QtNetwork.QNetworkProxy.NoProxy)) + self.timer = QtCore.QTimer(self) + self.timer.setInterval(500) + self.timer.timeout.connect(self._probe) + self.kill_timer = QtCore.QTimer(self) + self.kill_timer.setSingleShot(True) + self.kill_timer.timeout.connect(self._kill_if_stopping) + self.reply = None + self.state = "Stopped" + self.url = "" + self.deadline = 0 + self._decoder = codecs.getincrementaldecoder("utf-8")("replace") + + @property + def active(self): + """Return whether this manager still owns a live or starting process.""" + return self.process.state() != QtCore.QProcess.NotRunning + + def _set_state(self, state): + self.state = state + self.changed.emit(state) + + def start(self, executable, arguments, port, environment=None): + """Launch on loopback, refusing an occupied port before readiness checks.""" + if self.active: + raise ValueError("This MCP server is already running.") + self.kill_timer.stop() + self._cancel_probe() + with socket.socket() as check: + if hasattr(socket, "SO_EXCLUSIVEADDRUSE"): + check.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + check.bind(("127.0.0.1", port)) + self.url = f"http://127.0.0.1:{port}/mcp" + self._decoder = codecs.getincrementaldecoder("utf-8")("replace") + self.process.setProcessEnvironment(process_environment(environment)) + self.deadline = time.monotonic() + 60 + self._set_state("Starting; waiting for MCP handshake…") + self.process.start(str(executable), arguments) + self.timer.start() + + def _read(self): + self.output.emit( + self._decoder.decode(bytes(self.process.readAllStandardOutput())) + ) + + def _probe(self): + if time.monotonic() > self.deadline: + self.output.emit("\nMCP readiness timed out after 60 seconds.\n") + self.stop() + return + if self.reply is not None or not self.active: + return + request = QtNetwork.QNetworkRequest(QtCore.QUrl(self.url)) + request.setHeader( + QtNetwork.QNetworkRequest.ContentTypeHeader, "application/json" + ) + request.setRawHeader(b"Accept", b"application/json, text/event-stream") + request.setTransferTimeout(1500) + body = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-03-26", + "capabilities": {}, + "clientInfo": {"name": "Ansys Python Manager", "version": "1"}, + }, + } + reply = self.network.post(request, json.dumps(body).encode()) + self.reply = reply + reply.finished.connect(self._probe_finished) + + @QtCore.Slot() + def _probe_finished(self): + reply = self.sender() + if reply is not self.reply: + reply.deleteLater() + return + self.reply = None + payload = ( + bytes(reply.readAll()).decode("utf-8", errors="replace") + if reply.isOpen() + else "" + ) + status = reply.attribute(QtNetwork.QNetworkRequest.HttpStatusCodeAttribute) + session = next( + ( + bytes(value) + for name, value in reply.rawHeaderPairs() + if bytes(name).lower() == b"mcp-session-id" + ), + b"", + ) + reply.deleteLater() + if not self.timer.isActive() or status != 200: + return + messages = ( + [payload] + if payload.lstrip().startswith("{") + else [ + line[5:].strip() + for line in payload.splitlines() + if line.startswith("data:") + ] + ) + for message in messages: + try: + response = json.loads(message) + result = response.get("result", {}) + if response.get("id") != 1 or not all( + key in result + for key in ("protocolVersion", "serverInfo", "capabilities") + ): + continue + except (ValueError, AttributeError, TypeError): + continue + self.timer.stop() + self._set_state(f"Ready: {self.url}") + if session: + request = QtNetwork.QNetworkRequest(QtCore.QUrl(self.url)) + request.setRawHeader(b"mcp-session-id", session) + cleanup = self.network.deleteResource(request) + cleanup.finished.connect(cleanup.deleteLater) + return + + def _error(self, error): + if error == QtCore.QProcess.FailedToStart: + self.timer.stop() + self._set_state(f"Failed to start: {self.process.errorString()}") + + def _finished(self, code, status): + self.timer.stop() + self.kill_timer.stop() + self._read() + self._cancel_probe() + self._set_state( + self.process.ownership_error + or ( + "Stopped" + if self.state == "Stopping…" + else f"Exited (code {code}); see log." + ) + ) + + def stop(self): + """Stop this manager's process, escalating to kill after two seconds.""" + self.timer.stop() + self._cancel_probe() + if self.active: + self._set_state("Stopping…") + self.process.terminate() + self.kill_timer.start(2000) + + def _cancel_probe(self): + reply = self.reply + self.reply = None + if reply is not None: + reply.abort() + reply.deleteLater() + + def _kill_if_stopping(self): + if self.state == "Stopping…" and self.active: + self.process.kill() + + def shutdown(self): + """Reap the owned process when the manager closes.""" + self.stop() + if self.active and not self.process.waitForFinished(2000): + self.process.kill() + self.process.waitForFinished(2000) diff --git a/src/ansys/tools/installer/mcp_profiles.py b/src/ansys/tools/installer/mcp_profiles.py new file mode 100644 index 00000000..8bdf7e47 --- /dev/null +++ b/src/ansys/tools/installer/mcp_profiles.py @@ -0,0 +1,269 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Preview and merge MCP profiles without replacing unrelated client settings.""" + +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import shutil + +import tomlkit + +from ansys.tools.installer.mcp_backend import atomic_write + +CLIENTS = ("VS Code", "Copilot CLI", "Claude Desktop", "Cursor", "Codex", "OpenCode") + + +def default_profile_path(client, home=None, environ=None, windows=None): + """Return each agent's personal configuration, respecting its home override.""" + home = Path.home() if home is None else Path(home) + environ = os.environ if environ is None else environ + windows = os.name == "nt" if windows is None else windows + config = Path(environ.get("XDG_CONFIG_HOME") or home / ".config") + paths = { + "VS Code": Path(environ.get("COPILOT_HOME") or home / ".copilot") + / "mcp-config.json", + "Copilot CLI": Path(environ.get("COPILOT_HOME") or home / ".copilot") + / "mcp-config.json", + "Claude Desktop": ( + Path(environ.get("APPDATA") or home / "AppData" / "Roaming") + if windows + else config + ) + / "Claude" + / "claude_desktop_config.json", + "Cursor": home / ".cursor" / "mcp.json", + "Codex": Path(environ.get("CODEX_HOME") or home / ".codex") / "config.toml", + "OpenCode": config / "opencode" / "opencode.json", + } + return paths[client] + + +def _unique_object(pairs): + data = {} + for key, value in pairs: + if key in data: + raise ValueError(f"Duplicate JSON key: {key}") + data[key] = value + return data + + +def _profile_keys(servers, product): + def normalized(name): + return "".join(char for char in name.casefold() if char.isalnum()) + + aliases = { + normalized(name) + for name in ( + product.key, + f"{product.key}-mcp", + product.package, + product.package.removeprefix("ansys-"), + ) + } + keys = [key for key in servers if normalized(key) in aliases] + if keys: + canonical = f"{product.key}-mcp" + return sorted(keys, key=lambda key: key != canonical) + module = product.package.replace("-", ".") + for key, value in servers.items(): + if not isinstance(value, dict): + continue + command = value.get("command", "") + argv = ( + [*command] + if isinstance(command, list) + else [command, *value.get("args", [])] + ) + launcher = any( + isinstance(token, str) + and token.replace("\\", "/").rsplit("/", 1)[-1].removesuffix(".exe") + == product.package + for token in argv + ) + module_launch = any( + argv[i : i + 2] == ["-m", module] for i in range(len(argv) - 1) + ) + if launcher or module_launch: + keys.append(key) + if len(keys) > 1: + raise ValueError( + f"Multiple custom configurations launch {product.name}. Select or consolidate the intended entry in the file before reviewing; no changes were made." + ) + return keys + + +def _merge_missing(target, source): + for key, value in source.items(): + if key not in target: + target[key] = value + elif isinstance(target[key], dict) and isinstance(value, dict): + _merge_missing(target[key], value) + + +def _server_container(data, client, vscode_legacy=False): + name = ( + "mcp_servers" + if client == "Codex" + else ( + "servers" + if client == "VS Code" and vscode_legacy + else "mcp" if client == "OpenCode" else "mcpServers" + ) + ) + servers = data.setdefault(name, tomlkit.table() if client == "Codex" else {}) + if not isinstance(servers, dict): + raise ValueError(f"{name} must contain an object/table.") + if client == "OpenCode": + # Existing V1 files retain their layout; new files use the V2 schema. + legacy = any( + key != "servers" + and isinstance(value, dict) + and ( + value.get("type") in ("local", "remote") + or "command" in value + or "url" in value + ) + for key, value in servers.items() + ) + if "servers" in servers and legacy: + raise ValueError( + "OpenCode configuration mixes V1 and V2 layouts. Migrate it before reviewing; no changes were made." + ) + if not legacy: + servers = servers.setdefault("servers", {}) + if not isinstance(servers, dict): + raise ValueError("mcp.servers must contain an object.") + return servers + + +def render_profile( + client, + original, + product, + executable, + arguments, + *, + transport="stdio", + port=8080, + vscode_legacy=False, + environment=None, +): + """Merge a single product while preserving other servers and user preferences.""" + if client not in CLIENTS: + raise ValueError("Unknown MCP client.") + if transport not in ("stdio", "http"): + raise ValueError("Unknown MCP transport.") + if transport == "http" and product.http_flags is None: + raise ValueError(f"{product.name} only supports stdio.") + if transport == "http" and client == "Claude Desktop": + raise ValueError("Use stdio for Claude Desktop's local configuration file.") + data = ( + tomlkit.parse(original) + if client == "Codex" + else ( + json.loads(original, object_pairs_hook=_unique_object) + if original.strip() + else {} + ) + ) + if not isinstance(data, dict): + raise ValueError("The client configuration must contain an object.") + servers = _server_container(data, client, vscode_legacy) + matches = _profile_keys(servers, product) + key = matches[0] if matches else f"{product.key}-mcp" + profile = servers.setdefault(key, tomlkit.table() if client == "Codex" else {}) + if not isinstance(profile, dict): + raise ValueError(f"The existing {key} entry must contain an object/table.") + for duplicate in matches[1:]: + if not isinstance(servers[duplicate], dict): + raise ValueError( + f"The existing {duplicate} entry must contain an object/table." + ) + _merge_missing(profile, servers[duplicate]) + del servers[duplicate] + if transport == "stdio": + for field in ( + "url", + "headers", + "http_headers", + "env_http_headers", + "bearer_token_env_var", + "oauth", + "type", + ): + profile.pop(field, None) + profile["command"] = ( + [str(executable), *arguments] if client == "OpenCode" else str(executable) + ) + if client == "OpenCode": + profile.pop("args", None) + profile["type"] = "local" + else: + profile["args"] = list(arguments) + if client in ("VS Code", "Copilot CLI"): + profile["type"] = "local" if client == "Copilot CLI" else "stdio" + if environment: + field = "environment" if client == "OpenCode" else "env" + overrides = profile.setdefault(field, {}) + if not isinstance(overrides, dict): + raise ValueError(f"{key}.{field} must contain an object/table.") + overrides.update(environment) + else: + for field in ( + "command", + "args", + "env", + "environment", + "env_vars", + "cwd", + "type", + ): + profile.pop(field, None) + profile["url"] = f"http://127.0.0.1:{port}/mcp" + if client in ("VS Code", "Copilot CLI", "OpenCode"): + profile["type"] = "remote" if client == "OpenCode" else "http" + if client == "Codex": + profile.setdefault("startup_timeout_sec", 60) + return tomlkit.dumps(data) + if client == "Copilot CLI": + profile.setdefault("tools", ["*"]) + return json.dumps(data, indent=2, ensure_ascii=False) + "\n" + + +def save_profile(path, original, rendered): + """Back up and atomically save only if the file still matches its preview.""" + path = Path(path) + current = path.read_text(encoding="utf-8") if path.exists() else "" + if current != original: + raise ValueError( + "Configuration changed since preview. Preview it again before saving." + ) + backup = None + if path.exists(): + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ") + backup = path.with_name(f"{path.name}.{stamp}.bak") + shutil.copy2(path, backup) + atomic_write(path, rendered) + return backup diff --git a/src/ansys/tools/installer/mcp_releases.py b/src/ansys/tools/installer/mcp_releases.py new file mode 100644 index 00000000..b71e2f8a --- /dev/null +++ b/src/ansys/tools/installer/mcp_releases.py @@ -0,0 +1,212 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Resolve exact MCP releases and validate their supported Python interpreters.""" + +from dataclasses import dataclass +from email.parser import Parser +import json +import os +from pathlib import Path +import subprocess +import zipfile + +from packaging.specifiers import SpecifierSet +from packaging.utils import canonicalize_name, parse_wheel_filename +from packaging.version import Version +import requests +import tomlkit + + +@dataclass(frozen=True) +class ReleaseInfo: + """Describe the exact package selected for an installation.""" + + version: str + requires_python: str + requirement: str + + +@dataclass(frozen=True) +class PythonInfo: + """Describe a selected interpreter without importing any third-party package.""" + + executable: str + version: str + bits: int + + +def _requires_python(value, fallback): + result = value or fallback + SpecifierSet(result) + return result + + +def published_release(product, version=""): + """Resolve latest or a requested release from PyPI, without compatible fallback.""" + suffix = f"/{Version(version)}" if version else "" + response = requests.get( + f"https://pypi.org/pypi/{product.package}{suffix}/json", timeout=20 + ) + response.raise_for_status() + data = response.json() + info = data["info"] + resolved = str(Version(info["version"])) + if canonicalize_name(info["name"]) != canonicalize_name(product.package): + raise ValueError("PyPI returned metadata for a different package.") + if version and Version(resolved) != Version(version): + raise ValueError("PyPI returned a different release from the selected version.") + files = data.get("urls", []) + if not files or all(file.get("yanked", False) for file in files): + raise ValueError( + f"{product.name} {resolved} has no non-yanked distribution files." + ) + return ReleaseInfo( + resolved, + _requires_python(info.get("requires_python"), product.python), + f"{product.package}=={resolved}", + ) + + +def source_release(product, branch, requirement): + """Read the Python declaration from the selected official Git source.""" + response = requests.get( + f"https://api.github.com/repos/ansys/{product.key}-mcp/contents/pyproject.toml", + params={"ref": branch}, + headers={"Accept": "application/vnd.github.raw+json"}, + timeout=20, + ) + response.raise_for_status() + project = tomlkit.parse(response.text)["project"] + if canonicalize_name(project["name"]) != canonicalize_name(product.package): + raise ValueError("The Git source declares a different package name.") + return ReleaseInfo( + f"Git: {branch}", + _requires_python(project.get("requires-python"), product.python), + requirement, + ) + + +def wheelhouse_release(product, directory, version=""): + """Resolve the newest stable local wheel, or the explicitly selected version.""" + candidates = [] + for path in Path(directory).glob("*.whl"): + name, candidate, _build, _tags = parse_wheel_filename(path.name) + if canonicalize_name(name) == canonicalize_name(product.package): + if (version and candidate == Version(version)) or ( + not version and not candidate.is_prerelease + ): + candidates.append((candidate, path)) + if not candidates: + raise ValueError( + f"No wheel for {product.package}{'==' + version if version else ''} was found in the wheelhouse." + ) + selected = max(candidate for candidate, _path in candidates) + requirements = set() + for candidate, path in candidates: + if candidate != selected: + continue + with zipfile.ZipFile(path) as archive: + metadata = [ + name + for name in archive.namelist() + if name.endswith(".dist-info/METADATA") + ] + if len(metadata) != 1: + raise ValueError( + f"Wheel has invalid distribution metadata: {path.name}" + ) + message = Parser().parsestr(archive.read(metadata[0]).decode("utf-8")) + if ( + canonicalize_name(message["Name"] or "") + != canonicalize_name(product.package) + or Version(message["Version"]) != selected + ): + raise ValueError( + f"Wheel metadata does not match its filename: {path.name}" + ) + requirements.add( + _requires_python(message.get("Requires-Python"), product.python) + ) + # A release can contain platform wheels with different declarations. The + # shared supported range is safe for every wheel the resolver might select. + requires_python = str(SpecifierSet(",".join(sorted(requirements)))) + return ReleaseInfo(str(selected), requires_python, f"{product.package}=={selected}") + + +def inspect_python(executable): + """Probe Python with a timeout and no inherited Python startup configuration.""" + path = Path(executable).expanduser().absolute() + if not path.is_file(): + raise ValueError(f"Python executable not found: {path}") + environment = os.environ.copy() + for name in ("PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV"): + environment.pop(name, None) + command = [ + str(path), + "-I", + "-c", + "import json,platform,struct; print(json.dumps({'version':platform.python_version(),'bits':struct.calcsize('P')*8}))", + ] + result = subprocess.run( + command, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=True, + timeout=15, + env=environment, + **({"creationflags": subprocess.CREATE_NO_WINDOW} if os.name == "nt" else {}), + ) + data = json.loads(result.stdout) + return PythonInfo(str(path), str(Version(data["version"])), int(data["bits"])) + + +def validate_python(info, product, release): + """Enforce both published release metadata and the documented product range.""" + required = SpecifierSet(release.requires_python) & SpecifierSet(product.python) + if info.bits != 64 or Version(info.version) not in required: + raise ValueError( + f"{product.name} {release.version} requires 64-bit Python {required}; " + f"the selected interpreter is Python {info.version} ({info.bits}-bit). " + "Choose a supported Python in Create virtual environments or install one in Install Python." + ) + return info + + +def compatible_python(product, release, preferred, candidates=()): + """Keep a compatible chosen interpreter, otherwise choose an installed one.""" + errors = [] + for executable in dict.fromkeys([preferred, *candidates]): + if not executable: + continue + try: + return validate_python(inspect_python(executable), product, release) + except (OSError, ValueError, subprocess.SubprocessError) as error: + errors.append(str(error)) + raise ValueError( + f"No installed 64-bit Python satisfies {product.name} {release.version} " + f"({release.requires_python}; documented support {product.python}). " + "Install a supported Python using Install Python, then retry." + + (f"\n{errors[0]}" if errors else "") + ) diff --git a/src/ansys/tools/installer/mcp_tab.py b/src/ansys/tools/installer/mcp_tab.py new file mode 100644 index 00000000..006d1b6e --- /dev/null +++ b/src/ansys/tools/installer/mcp_tab.py @@ -0,0 +1,2030 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Native Qt installation, server and coding-agent controls for PyAnsys MCPs.""" + +import json +import os +from pathlib import Path +import sys +import tempfile +import time + +from PySide6 import QtCore, QtGui, QtWidgets +from packaging.specifiers import SpecifierSet +from packaging.version import InvalidVersion, Version + +from ansys.tools.installer.installed_table import DataComboBox +from ansys.tools.installer.mcp_backend import ( + application_directory, + atomic_write, + available_versions, + console_executable, + environment_base_python, + installed_version, + managed_environment, + package_requirement, + prepare_installation, + python_executable, + read_settings, + server_arguments, +) +from ansys.tools.installer.mcp_catalog import PRODUCTS +from ansys.tools.installer.mcp_compatibility import check_compatibility +from ansys.tools.installer.mcp_launch import launch_options, option_arguments +from ansys.tools.installer.mcp_process import CommandQueue, McpServer +from ansys.tools.installer.mcp_profiles import ( + CLIENTS, + default_profile_path, + render_profile, + save_profile, +) + + +class _Signals(QtCore.QObject): + completed = QtCore.Signal(object, object) + finished = QtCore.Signal(object) + + +class _Task(QtCore.QRunnable): + def __init__(self, function): + super().__init__() + self.function = function + self.signals = _Signals() + + def run(self): + try: + result, error = self.function(), None + except Exception as failure: + result, error = None, str(failure) + try: + self.signals.completed.emit(result, error) + self.signals.finished.emit(self) + except RuntimeError as error: + # QApplication can destroy signal objects while a metadata request + # finishes during shutdown. There is no remaining UI to notify. + if "deleted" not in str(error): + raise + + +class _ReleaseCombo(QtWidgets.QComboBox): + requested = QtCore.Signal() + + def showPopup(self): + self.requested.emit() + super().showPopup() + + +class McpTab(QtWidgets.QWidget): + """Manage independently installed PyAnsys MCP servers and client profiles.""" + + def __init__(self, parent=None, directory=None): + """Build the tab without fetching metadata or installing packages on startup.""" + super().__init__(parent) + self._manager = parent + self.directory = Path(directory) if directory else application_directory() + self.settings_path = self.directory / "settings.json" + self._settings_error = None + try: + self.settings = read_settings(self.settings_path) + except (OSError, ValueError) as error: + self.settings = {} + self._settings_error = str(error) + self._selected = None + self._loading = False + self._preparing = False + self._prepare_cancelled = False + self._closed = False + self._tasks = [] + self._versions = {} + self._version_pending = set() + self._discovery_pending = False + self._discovered = False + self._launch_schema = [] + self._launch_values = {} + self._launch_context = None + self._launch_pending = set() + self._wheelhouse = None + self._profile_preview = None + self._compatibility = None + self._compatibility_revision = 0 + self._compatibility_pending = False + self._compatibility_error = "" + self._probe_cache = {} + self._manual_pythons = set() + self._manual_environments = set() + self._compatibility_timer = QtCore.QTimer(self) + self._compatibility_timer.setSingleShot(True) + self._compatibility_timer.setInterval(350) + self._compatibility_timer.timeout.connect(self._check_compatibility) + self._logs = {product.key: "" for product in PRODUCTS} + self.servers = {product.key: McpServer(self) for product in PRODUCTS} + for key, server in self.servers.items(): + server.output.connect( + lambda message, key=key: self._append_log(key, message) + ) + server.changed.connect(lambda _state, key=key: self._server_changed(key)) + self.queue = CommandQueue(self) + self.queue.output.connect( + lambda message: self._append_log(self.product.key, message) + ) + self.queue.completed.connect(self._installed) + self._build() + self.product_select.currentIndexChanged.connect(self._select_product) + self._select_product(0) + if self._settings_error: + self._error(f"Could not read {self.settings_path}: {self._settings_error}") + QtWidgets.QApplication.instance().aboutToQuit.connect(self.shutdown) + + @property + def product(self): + """Return the selected catalog entry.""" + return PRODUCTS[self.product_select.currentIndex()] + + @property + def environment(self): + """Return a selected existing environment or the product's managed venv.""" + if self._custom_environment(): + value = self.environment_select.active_path + if not value: + raise ValueError("Choose an available virtual environment.") + if value == "None": + raise ValueError( + "No virtual environment found. Create one in Create virtual environments." + ) + return self._environment_root(value) + return managed_environment(self.directory, self.product, self._base_python()) + + def _custom_environment(self): + return self.environment_mode.currentData() == "existing" + + @staticmethod + def _environment_root(value): + root = Path(value).expanduser().absolute() + return root.parent if root.name in ("Scripts", "bin") else root + + def _base_python(self): + value = self.python_select.active_path + return self._python_choice(value) if value and value != "None" else "" + + @staticmethod + def _python_choice(value): + path = Path(value).expanduser().absolute() + if path.is_dir(): + return str(python_executable(path)) + name = path.name.lower() + if ( + name.endswith(".exe") + or name in ("python", "python3") + or name.startswith("python3.") + ): + return str(path) + return str(python_executable(path)) + + def _button(self, text, callback): + button = QtWidgets.QPushButton(text) + button.clicked.connect(lambda: self._try(callback)) + return button + + def _field_with_browse(self, field, callback): + widget = QtWidgets.QWidget() + row = QtWidgets.QHBoxLayout(widget) + row.setContentsMargins(0, 0, 0, 0) + row.addWidget(field, 1) + row.addWidget(self._button("Browse…", callback)) + return widget + + def _page(self, tabs, title): + scroll = QtWidgets.QScrollArea() + scroll.setWidgetResizable(True) + scroll.setFrameShape(QtWidgets.QFrame.NoFrame) + page = QtWidgets.QWidget() + layout = QtWidgets.QVBoxLayout(page) + scroll.setWidget(page) + tabs.addTab(scroll, title) + return layout + + @staticmethod + def _label(text=""): + label = QtWidgets.QLabel(text) + label.setWordWrap(True) + label.setTextFormat(QtCore.Qt.PlainText) + return label + + @staticmethod + def _compact_combo(combo): + combo.setSizeAdjustPolicy( + QtWidgets.QComboBox.AdjustToMinimumContentsLengthWithIcon + ) + combo.setMinimumContentsLength(20) + combo.setMinimumWidth(0) + combo.setSizePolicy( + QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed + ) + return combo + + def _section(self, title, parent_layout): + section = QtWidgets.QGroupBox(title) + section.setProperty("mcpSection", True) + contents = QtWidgets.QVBoxLayout(section) + contents.setContentsMargins(12, 18, 12, 12) + contents.setSpacing(8) + parent_layout.addWidget(section) + return section, contents + + @staticmethod + def _form(layout): + form = QtWidgets.QFormLayout() + form.setFieldGrowthPolicy(QtWidgets.QFormLayout.AllNonFixedFieldsGrow) + form.setRowWrapPolicy(QtWidgets.QFormLayout.WrapLongRows) + form.setHorizontalSpacing(12) + form.setVerticalSpacing(8) + layout.addLayout(form) + return form + + def _fold(self, title, parent_layout): + toggle = QtWidgets.QToolButton() + toggle.setText(title) + toggle.setCheckable(True) + toggle.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) + toggle.setArrowType(QtCore.Qt.RightArrow) + parent_layout.addWidget(toggle) + body = QtWidgets.QWidget() + contents = QtWidgets.QVBoxLayout(body) + contents.setContentsMargins(12, 4, 0, 8) + contents.setSpacing(8) + body.hide() + parent_layout.addWidget(body) + toggle.toggled.connect(body.setVisible) + toggle.toggled.connect( + lambda expanded: toggle.setArrowType( + QtCore.Qt.DownArrow if expanded else QtCore.Qt.RightArrow + ) + ) + return toggle, body, contents + + def _build(self): + self.setStyleSheet(""" + QGroupBox[mcpSection="true"] { + border: 1px solid palette(mid); border-radius: 5px; + margin-top: 10px; + } + QGroupBox[mcpSection="true"]::title { + subcontrol-origin: margin; left: 10px; padding: 0 4px; + font-weight: 600; + } + QComboBox, QLineEdit, QSpinBox { min-height: 26px; } + QPushButton { min-height: 28px; padding: 0 10px; } + QPushButton[primary="true"] { font-weight: 600; } + """) + layout = QtWidgets.QVBoxLayout(self) + layout.setContentsMargins(10, 8, 10, 8) + layout.setSpacing(8) + _header, header = self._section("MCP product", layout) + row = QtWidgets.QHBoxLayout() + self.product_select = self._compact_combo(QtWidgets.QComboBox()) + self.product_select.setAccessibleName("PyAnsys MCP product") + self.product_select.addItems([product.name for product in PRODUCTS]) + row.addWidget(self.product_select, 1) + self.installed_label = self._label() + row.addWidget(self.installed_label) + header.addLayout(row) + description_row = QtWidgets.QHBoxLayout() + self.description = self._label() + description_row.addWidget(self.description, 1) + self.guide = QtWidgets.QLabel() + self.guide.setOpenExternalLinks(True) + description_row.addWidget(self.guide) + header.addLayout(description_row) + self.pages = QtWidgets.QTabWidget() + layout.addWidget(self.pages, 1) + self._setup_page() + self._server_page() + self._client_page() + self.action_stack = QtWidgets.QStackedWidget() + for actions in (self.install_actions, self.server_actions, self.client_actions): + self.action_stack.addWidget(actions) + layout.addWidget(self.action_stack) + self.pages.currentChanged.connect(self.action_stack.setCurrentIndex) + self.progress = QtWidgets.QProgressBar() + self.progress.setRange(0, 0) + self.progress.setTextVisible(False) + self.progress.setFixedHeight(5) + self.progress.hide() + layout.addWidget(self.progress) + self.status = self._label("Select an MCP and an environment to get started.") + self.status.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse) + layout.addWidget(self.status) + self.log_group = QtWidgets.QToolButton() + self.log_group.setText("Activity log") + self.log_group.setCheckable(True) + self.log_group.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) + self.log_group.setArrowType(QtCore.Qt.RightArrow) + layout.addWidget(self.log_group) + self.log = QtWidgets.QPlainTextEdit() + self.log.setAccessibleName("Installation and server log") + self.log.setReadOnly(True) + self.log.setMaximumBlockCount(2000) + self.log.setMaximumHeight(145) + self.log.setFont(QtGui.QFontDatabase.systemFont(QtGui.QFontDatabase.FixedFont)) + self.log.hide() + layout.addWidget(self.log) + self.log_group.toggled.connect(self.log.setVisible) + self.log_group.toggled.connect( + lambda expanded: self.log_group.setArrowType( + QtCore.Qt.DownArrow if expanded else QtCore.Qt.RightArrow + ) + ) + + def _setup_page(self): + layout = self._page(self.pages, "Installation") + layout.setSpacing(10) + self.install_options = QtWidgets.QWidget() + options = QtWidgets.QVBoxLayout(self.install_options) + options.setContentsMargins(0, 0, 0, 0) + options.setSpacing(10) + self.environment_section, environment = self._section( + "Python environment", options + ) + mode_row = QtWidgets.QHBoxLayout() + self.environment_mode = self._compact_combo(QtWidgets.QComboBox()) + self.environment_mode.setAccessibleName("Installation environment") + self.environment_mode.addItem("Dedicated environment (recommended)", "managed") + self.environment_mode.addItem("Existing virtual environment", "existing") + mode_row.addWidget(self.environment_mode, 1) + self.refresh_choices_button = self._button("Refresh", self._refresh_choices) + self.refresh_choices_button.setToolTip( + "Refresh the Python and virtual environments discovered by APM." + ) + mode_row.addWidget(self.refresh_choices_button) + environment.addLayout(mode_row) + self.managed_panel = QtWidgets.QWidget() + managed = QtWidgets.QVBoxLayout(self.managed_panel) + managed.setContentsMargins(0, 0, 0, 0) + managed.setSpacing(4) + self.python_caption = self._label("Select Python version") + managed.addWidget(self.python_caption) + self.python_select = self._compact_combo( + DataComboBox( + installed_python=True, installed_forge=True, populate_on_init=False + ) + ) + self.python_select.setAccessibleName("Select Python version") + managed.addWidget(self.python_select) + self.managed_python_info = self._label() + managed.addWidget(self.managed_python_info) + environment.addWidget(self.managed_panel) + self.existing_panel = QtWidgets.QWidget() + existing = QtWidgets.QVBoxLayout(self.existing_panel) + existing.setContentsMargins(0, 0, 0, 0) + existing.setSpacing(4) + existing.addWidget(self._label("Available virtual environments")) + self.environment_select = self._compact_combo( + DataComboBox(created_venv=True, populate_on_init=False) + ) + self.environment_select.setAccessibleName("Available virtual environments") + existing.addWidget(self.environment_select) + environment.addWidget(self.existing_panel) + self.python_hint = self._label() + support = self._form(environment) + self.python_support = self._label() + support.addRow("Supported Python", self.python_support) + environment.addWidget(self.python_hint) + self.package_section, package = self._section("MCP package", options) + self.package_form = self._form(package) + self.source = self._compact_combo(QtWidgets.QComboBox()) + self.source.addItem("PyPI release", "release") + self.source.addItem("Official Git repository", "branch") + self.source.addItem("Offline wheelhouse", "offline") + self.package_form.addRow("Install from", self.source) + self.version = _ReleaseCombo() + self.version.requested.connect(self._fetch_versions) + self.version.setEditable(False) + self.version.addItem("Latest", "") + self.version.setToolTip("Latest is resolved again on every installation.") + self.version_row = QtWidgets.QWidget() + row = QtWidgets.QHBoxLayout(self.version_row) + row.setContentsMargins(0, 0, 0, 0) + row.addWidget(self.version, 1) + self.package_form.addRow("Version", self.version_row) + self.branch = QtWidgets.QLineEdit("main") + self.package_form.addRow("Branch / tag", self.branch) + self.wheelhouse_path = QtWidgets.QLineEdit() + self.wheelhouse_path.setPlaceholderText("Select a wheel folder or ZIP") + self.wheelhouse_row = self._field_with_browse( + self.wheelhouse_path, self._browse_wheelhouse + ) + self.package_form.addRow("Wheelhouse", self.wheelhouse_row) + self.source_hint = self._label() + package.addWidget(self.source_hint) + self.install_advanced_toggle, self.install_advanced, advanced = self._fold( + "Other locations and details", options + ) + self.location_details = self._label() + self.location_details.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse) + advanced.addWidget(self.location_details) + manual = QtWidgets.QHBoxLayout() + manual.addWidget(self._button("Add Python executable…", self._browse_python)) + manual.addWidget( + self._button("Add virtual environment…", self._browse_environment) + ) + advanced.addLayout(manual) + advanced.addWidget( + self._label( + "Manual Python selections can fall outside the documented range. The MCP package's own Python requirements still apply." + ) + ) + layout.addWidget(self.install_options) + layout.addStretch() + self.install_actions = QtWidgets.QWidget() + buttons = QtWidgets.QHBoxLayout(self.install_actions) + buttons.setContentsMargins(0, 0, 0, 0) + self.save_button = self._button("Save settings", self._save) + buttons.addWidget(self.save_button) + buttons.addStretch() + self.cancel_button = self._button("Cancel", self._cancel_install) + buttons.addWidget(self.cancel_button) + self.install_button = self._button("Install MCP", lambda: self._install(True)) + self.install_button.setProperty("primary", True) + buttons.addWidget(self.install_button) + self.environment_mode.currentIndexChanged.connect(self._options_changed) + for combo in (self.python_select, self.environment_select): + combo.currentIndexChanged.connect(self._options_changed) + self.python_select.currentIndexChanged.connect(self._requirements_changed) + self.source.currentIndexChanged.connect(self._requirements_changed) + self.version.currentTextChanged.connect(self._requirements_changed) + self.branch.textChanged.connect(self._requirements_changed) + self.wheelhouse_path.textChanged.connect(self._requirements_changed) + + def _server_page(self): + layout = self._page(self.pages, "Server settings") + layout.setSpacing(10) + layout.addWidget( + self._label( + "For a coding agent on this computer, use the automatic connection in Coding agents. Start HTTP here when you need a shared server." + ) + ) + self.server_options = QtWidgets.QWidget() + options = QtWidgets.QVBoxLayout(self.server_options) + options.setContentsMargins(0, 0, 0, 0) + options.setSpacing(10) + self.http_section, http = self._section("Local HTTP server", options) + form = self._form(http) + self.http_port = QtWidgets.QSpinBox() + self.http_port.setRange(1, 65535) + form.addRow("HTTP port", self.http_port) + self.endpoint = self._label() + self.endpoint.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse) + http.addWidget(self.endpoint) + self.server_status = self._label() + http.addWidget(self.server_status) + http.addWidget( + self._label( + "Available on this computer only. APM stops its servers when it closes." + ) + ) + self.stdio_notice, stdio = self._section("Automatic server", options) + stdio.addWidget( + self._label( + "This MCP uses stdio. Your coding agent starts and stops it automatically." + ) + ) + stdio.addWidget( + self._button("Set up coding agent", lambda: self.pages.setCurrentIndex(2)) + ) + self.solver_section, solver = self._section("Solver connection", options) + self.connect = QtWidgets.QCheckBox("Connect to a running solver on startup") + solver.addWidget(self.connect) + self.solver_fields = QtWidgets.QWidget() + solver_form = self._form(QtWidgets.QVBoxLayout(self.solver_fields)) + self.machine = QtWidgets.QLineEdit("127.0.0.1") + solver_form.addRow("Solver host", self.machine) + self.solver_port = QtWidgets.QSpinBox() + self.solver_port.setRange(1, 65535) + solver_form.addRow("Solver port", self.solver_port) + solver.addWidget(self.solver_fields) + self.server_advanced_toggle, self.server_advanced, advanced = self._fold( + "Advanced launch settings", options + ) + advanced.addWidget( + self._label( + "Applies to HTTP servers and automatic coding-agent connections." + ) + ) + self.aedt_section, aedt = self._section("PyAEDT options", advanced) + self.graphical = QtWidgets.QCheckBox("Open the AEDT graphical interface") + self.context = QtWidgets.QCheckBox("Include AEDT context tools") + self.dynamic = QtWidgets.QCheckBox("Enable dynamic tool discovery") + for field in (self.graphical, self.context, self.dynamic): + aedt.addWidget(field) + _launch, launch = self._section("Available launch options", advanced) + self.launch_hint = self._label( + "Expand advanced settings to read options from the installed MCP." + ) + launch.addWidget(self.launch_hint) + self.launch_choice = self._compact_combo(QtWidgets.QComboBox()) + self.launch_choice.setAccessibleName("Add launch option") + launch.addWidget(self.launch_choice) + self.launch_rows = QtWidgets.QVBoxLayout() + launch.addLayout(self.launch_rows) + self.launch_choice.activated.connect(self._add_launch_option) + self.server_advanced_toggle.toggled.connect( + lambda expanded: self._load_launch_options() if expanded else None + ) + self.raw_arguments_toggle, _raw, raw = self._fold("Custom arguments", advanced) + raw.addWidget( + self._label( + "For expert use. Prefer the available options above. Enter a JSON array with each option and value as a separate string." + ) + ) + self.extra = QtWidgets.QPlainTextEdit("[]") + self.extra.setAccessibleName("Additional launch arguments") + self.extra.setMaximumHeight(75) + raw.addWidget(self.extra) + _variables, variables = self._section("Environment variables", advanced) + variables.addWidget( + self._label( + 'JSON object, for example {"NAME": "value"}. Values are saved as plain text.' + ) + ) + self.environment_json = QtWidgets.QPlainTextEdit("{}") + self.environment_json.setAccessibleName("Environment variables") + self.environment_json.setMaximumHeight(75) + variables.addWidget(self.environment_json) + layout.addWidget(self.server_options) + layout.addStretch() + self.server_actions = QtWidgets.QWidget() + actions = QtWidgets.QVBoxLayout(self.server_actions) + actions.setContentsMargins(0, 0, 0, 0) + buttons = QtWidgets.QHBoxLayout() + self.server_save_button = self._button("Save settings", self._save) + buttons.addWidget(self.server_save_button) + buttons.addStretch() + self.stop_button = self._button( + "Stop server", lambda: self.servers[self.product.key].stop() + ) + buttons.addWidget(self.stop_button) + self.start_button = self._button("Start HTTP server", self._start_server) + self.start_button.setProperty("primary", True) + buttons.addWidget(self.start_button) + actions.addLayout(buttons) + self.connect.toggled.connect(self._options_changed) + self.http_port.valueChanged.connect(self._options_changed) + + def _client_page(self): + layout = self._page(self.pages, "Coding agents") + layout.setSpacing(10) + self.client_section, client = self._section("Agent connection", layout) + form = self._form(client) + self.client = self._compact_combo(QtWidgets.QComboBox()) + self.client.addItems(CLIENTS) + form.addRow("Coding agent", self.client) + self.transport = self._compact_combo(QtWidgets.QComboBox()) + form.addRow("Connection", self.transport) + self.client_hint = self._label() + client.addWidget(self.client_hint) + self.profile_section, profile = self._section("Configuration file", layout) + self.vscode_format = self._compact_combo(QtWidgets.QComboBox()) + self.vscode_format.addItem("Copilot harness (current)", False) + self.vscode_format.addItem("Local harness (legacy)", True) + self.vscode_format.setAccessibleName("VS Code configuration format") + self.vscode_controls = QtWidgets.QWidget() + vscode_row = QtWidgets.QHBoxLayout(self.vscode_controls) + vscode_row.setContentsMargins(0, 0, 0, 0) + vscode_row.addWidget(self.vscode_format, 1) + self.workspace_button = self._button( + "Choose workspace…", self._browse_workspace + ) + vscode_row.addWidget(self.workspace_button) + profile.addWidget(self.vscode_controls) + self.profile_path = QtWidgets.QLineEdit() + self.profile_path.setAccessibleName("Coding agent configuration file") + profile.addWidget( + self._field_with_browse(self.profile_path, self._browse_profile) + ) + self.profile_hint = self._label() + profile.addWidget(self.profile_hint) + self.preview_section, preview = self._section("Review configuration", layout) + self.preview = QtWidgets.QPlainTextEdit() + self.preview.setReadOnly(True) + self.preview.setAccessibleName("Configuration preview") + self.preview.setFont( + QtGui.QFontDatabase.systemFont(QtGui.QFontDatabase.FixedFont) + ) + self.preview.setMinimumHeight(130) + preview.addWidget(self.preview) + self.preview_section.hide() + layout.addStretch() + self.client_actions = QtWidgets.QWidget() + buttons = QtWidgets.QHBoxLayout(self.client_actions) + buttons.setContentsMargins(0, 0, 0, 0) + buttons.addStretch() + self.write_profile_button = self._button( + "Review configuration…", self._review_or_write_profile + ) + self.write_profile_button.setProperty("primary", True) + buttons.addWidget(self.write_profile_button) + self.client.currentTextChanged.connect(self._client_changed) + self.transport.currentIndexChanged.connect(self._connection_changed) + self.profile_path.textChanged.connect(self._invalidate_preview) + self.vscode_format.currentIndexChanged.connect(self._vscode_format_changed) + self.http_port.valueChanged.connect(self._invalidate_preview) + self.extra.textChanged.connect(self._launch_options_changed) + self.environment_json.textChanged.connect(self._launch_options_changed) + for field in (self.connect, self.graphical, self.context, self.dynamic): + field.toggled.connect(self._launch_options_changed) + self.machine.textChanged.connect(self._invalidate_preview) + self.solver_port.valueChanged.connect(self._invalidate_preview) + self._client_changed() + + def _try(self, action): + try: + action() + except Exception as error: + self._error(str(error)) + + def _error(self, message): + self.status.setText(message) + self._append_log(self.product.key, f"\nError: {message}\n") + self.log_group.setChecked(True) + + def _append_log(self, key, message): + self._logs[key] = (self._logs[key] + message)[-150000:] + if self.product.key == key: + self.log.moveCursor(QtGui.QTextCursor.End) + self.log.insertPlainText(message) + self.log.moveCursor(QtGui.QTextCursor.End) + + def _select_product(self, index): + if self._selected is not None: + try: + self._save(self._selected, announce=False) + except (OSError, ValueError) as error: + self.product_select.blockSignals(True) + self.product_select.setCurrentIndex(self._selected) + self.product_select.blockSignals(False) + self._error(str(error)) + return + self._selected = index + self._loading = True + product = self.product + values = self.settings.get(product.key, {}) + self.description.setText(product.description) + self.guide.setText(f'Documentation ↗') + legacy_python = environment_base_python( + self.directory / "environments" / product.key + ) + selected_python = str(values.get("base_python", self._base_python())) + if legacy_python and not values.get("managed_selection", False): + selected_python = legacy_python + if ( + not selected_python + and self._manager is not None + and hasattr(self._manager, "venv_table_tab") + ): + path = self._manager.venv_table_tab.table.active_path + if path and path != "None": + selected_python = self._python_choice(path) + if not selected_python and not getattr(sys, "frozen", False): + selected_python = sys.executable + if selected_python: + self.select_python( + selected_python, manual=values.get("manual_python", False) is True + ) + selected_environment = str(values.get("environment", "")) + if selected_environment: + self._manual_environments.add(selected_environment) + self._select_path(self.environment_select, selected_environment) + self.environment_mode.setCurrentIndex( + 1 if values.get("custom", False) is True else 0 + ) + self.source.setCurrentIndex( + 2 + if values.get("offline", False) is True + else 1 if values.get("source") == "branch" else 0 + ) + self.version.clear() + self.version.addItem("Latest", "") + version = str(values.get("version", "")) + if version: + self.version.addItem(version, version) + self.version.setCurrentIndex(1) + self.branch.setText(str(values.get("branch", "main"))) + self.wheelhouse_path.setText(str(values.get("wheelhouse", ""))) + self.http_port.setValue(self._port(values.get("http_port"), 8080 + index)) + self.solver_port.setValue( + self._port(values.get("solver_port"), product.product_port or 50051) + ) + self.connect.setChecked(values.get("connect", False) is True) + self.machine.setText(str(values.get("machine", "127.0.0.1"))) + self.graphical.setChecked(values.get("graphical", False) is True) + self.context.setChecked(values.get("context", False) is True) + self.dynamic.setChecked(values.get("dynamic", False) is True) + self.extra.setPlainText(str(values.get("extra", "[]"))) + self._launch_values = dict(values.get("launch_options", {})) + self._launch_schema = [] + self._launch_context = None + self.launch_hint.setText( + "Expand advanced settings to read options from the installed MCP." + ) + self._render_launch_options() + self.environment_json.setPlainText(str(values.get("env", "{}"))) + self.client.setCurrentText(str(values.get("client", self.client.currentText()))) + legacy = values.get( + "vscode_legacy", str(values.get("profile_path", "")).endswith("mcp.json") + ) + self.vscode_format.setCurrentIndex(1 if legacy else 0) + self._update_transports(str(values.get("transport", "stdio"))) + if str(values.get("profile_path", "")).strip(): + self.profile_path.setText(str(values["profile_path"])) + self.server_advanced_toggle.setChecked(False) + self.install_advanced_toggle.setChecked(False) + self.log.setPlainText(self._logs[product.key]) + self._loading = False + self._requirements_changed() + if self.isVisible(): + self._fetch_versions() + if self._launch_values: + self._load_launch_options() + + @staticmethod + def _port(value, default): + return value if type(value) is int and 1 <= value <= 65535 else default + + def _version(self): + return ( + "" + if self.version.currentText().strip().lower() + in ("latest", "latest compatible", "") + else self.version.currentText().strip() + ) + + def _save(self, index=None, announce=True): + if self._settings_error: + raise ValueError( + f"Repair {self.settings_path} before saving: {self._settings_error}" + ) + index = self.product_select.currentIndex() if index is None else index + self.settings[PRODUCTS[index].key] = { + "base_python": self._base_python(), + "managed_selection": True, + "manual_python": self._base_python() in self._manual_pythons, + "custom": self._custom_environment(), + "environment": self._selected_environment_path(), + "source": "branch" if self.source.currentData() == "branch" else "release", + "version": self._version(), + "branch": self.branch.text().strip(), + "offline": self.source.currentData() == "offline", + "wheelhouse": self.wheelhouse_path.text().strip(), + "http_port": self.http_port.value(), + "solver_port": self.solver_port.value(), + "connect": self.connect.isChecked(), + "machine": self.machine.text().strip(), + "graphical": self.graphical.isChecked(), + "context": self.context.isChecked(), + "dynamic": self.dynamic.isChecked(), + "extra": self.extra.toPlainText(), + "launch_options": dict(self._launch_values), + "env": self.environment_json.toPlainText(), + "client": self.client.currentText(), + "vscode_legacy": self.vscode_format.currentData(), + "profile_path": self.profile_path.text().strip(), + "transport": self._transport(), + } + atomic_write(self.settings_path, json.dumps(self.settings, indent=2) + "\n") + if announce: + self.status.setText("MCP settings saved.") + + def _selected_environment_path(self): + value = self.environment_select.active_path + return str(self._environment_root(value)) if value and value != "None" else "" + + @staticmethod + def _same_path(left, right): + return os.path.normcase(os.path.abspath(left)) == os.path.normcase( + os.path.abspath(right) + ) + + def _choice_executable(self, combo, index): + data = combo.itemData(index) or {} + value = data.get("path", "") + if not value or value == "None": + return "" + if combo is self.environment_select: + value = self._environment_root(value) + return ( + str(python_executable(value)) + if combo is self.environment_select + else self._python_choice(value) + ) + + def _select_path(self, combo, value): + target = ( + self._python_choice(value) + if combo is self.python_select + else str(self._environment_root(value)) + ) + for index in range(combo.count()): + data = combo.itemData(index) or {} + path = data.get("path", "") + if not path or path == "None": + continue + candidate = ( + self._python_choice(path) + if combo is self.python_select + else str(self._environment_root(path)) + ) + if self._same_path(candidate, target): + combo.setCurrentIndex(index) + return + label = ( + f"Python — {target}" + if combo is self.python_select + else f"{Path(target).name} — {target}" + ) + combo.addItem( + label, + { + "path": target, + "version": ( + "Python" if combo is self.python_select else Path(target).name + ), + "admin": "False", + }, + ) + combo.setItemData(combo.count() - 1, target, QtCore.Qt.ToolTipRole) + combo.setCurrentIndex(combo.count() - 1) + + def select_python(self, executable, manual=True): + """Select an interpreter using the same discovered choices as Create environments.""" + if manual: + self._manual_pythons.add(self._python_choice(executable)) + self._select_path(self.python_select, executable) + self._requirements_changed() + + def select_environment(self, directory): + """Select an existing environment from APM's shared environment dropdown.""" + self._manual_environments.add(str(directory)) + self._select_path(self.environment_select, directory) + self.environment_mode.setCurrentIndex(1) + self._requirements_changed() + + def _apply_choices(self, snapshots): + preferred = (self._base_python(), self._selected_environment_path()) + self._loading = True + for combo, entries, manual, selected in zip( + (self.python_select, self.environment_select), + snapshots, + (self._manual_pythons, self._manual_environments), + preferred, + ): + with QtCore.QSignalBlocker(combo): + combo.set_entries(entries) + for value in sorted(manual): + self._select_path(combo, value) + if selected: + self._select_path(combo, selected) + self._loading = False + self._discovered = True + self._requirements_changed() + + def _refresh_choices(self): + if ( + self.queue.active + or self._preparing + or self._closed + or self._discovery_pending + ): + return + self._discovery_pending = True + self.refresh_choices_button.setEnabled(False) + self._background( + lambda: (self.python_select.discover(), self.environment_select.discover()), + self._choices_discovered, + ) + + @QtCore.Slot(object, object) + def _choices_discovered(self, snapshots, error): + self._discovery_pending = False + if self._closed: + return + self.refresh_choices_button.setEnabled(True) + if error: + self._error(f"Could not refresh environments: {error}") + else: + self._launch_context = None + self._apply_choices(snapshots) + if self.server_advanced_toggle.isChecked(): + self._load_launch_options() + + def showEvent(self, event): + """Reuse APM's discovery snapshots; never run subprocesses on tab selection.""" + super().showEvent(event) + manager = self._manager + if manager is not None and hasattr(manager, "installed_table_tab"): + sources = ( + manager.venv_table_tab.table, + manager.installed_table_tab.venv_table, + ) + snapshots = tuple( + [(combo.itemText(i), combo.itemData(i)) for i in range(combo.count())] + for combo in sources + ) + if snapshots != getattr(self, "_shared_choices", None): + self._shared_choices = snapshots + self._apply_choices(snapshots) + elif not self._discovered: + self._refresh_choices() + if self._compatibility is None and not self._compatibility_pending: + self._requirements_changed() + self._fetch_versions() + if self._launch_values: + self._load_launch_options() + + def _options_changed(self): + if self._loading: + return + self._invalidate_preview() + self._refresh() + if self.server_advanced_toggle.isChecked(): + self._load_launch_options() + + def _set_choice_enabled(self, combo, index, enabled, reason=""): + item = combo.model().item(index) + item.setEnabled(enabled) + item.setSelectable(enabled) + role = QtCore.Qt.UserRole + 1 + label = combo.itemData(index, role) + if label is None: + label = combo.itemText(index) + combo.setItemData(index, label, role) + combo.setItemText(index, label if enabled else f"Unavailable · {label}") + data = combo.itemData(index) or {} + combo.setItemData(index, reason or data.get("path", ""), QtCore.Qt.ToolTipRole) + if combo is self.python_select: + manual = self._choice_executable(combo, index) in self._manual_pythons + item.setEnabled(enabled or manual) + item.setSelectable(enabled or manual) + combo.view().setRowHidden(index, not enabled and not manual) + if manual and not enabled: + combo.setItemText(index, f"Manual · {label}") + + def _choose_supported_python(self): + combo = self.python_select + if ( + combo.currentIndex() >= 0 + and combo.model().item(combo.currentIndex()).isEnabled() + ): + return + with QtCore.QSignalBlocker(combo): + combo.setCurrentIndex( + next( + ( + index + for index in range(combo.count()) + if combo.model().item(index).isEnabled() + ), + -1, + ) + ) + + def _catalog_filter(self): + for combo in (self.python_select, self.environment_select): + for index in range(combo.count()): + data = combo.itemData(index) or {} + enabled = bool(self._choice_executable(combo, index)) + reason = "" + if combo is self.python_select and data.get("version", "").startswith( + "Python " + ): + try: + enabled = enabled and Version( + data["version"].split(" ", 1)[1] + ) in SpecifierSet(self.product.python) + if not enabled: + reason = f"{self.product.name} supports 64-bit Python {self.product.python}." + except InvalidVersion: + pass + self._set_choice_enabled(combo, index, enabled, reason) + self._choose_supported_python() + + def _requirements_changed(self, *_): + if self._loading or self._closed: + return + self._compatibility_revision += 1 + self._compatibility = None + self._compatibility_error = "" + self._compatibility_pending = False + self._compatibility_timer.stop() + self._catalog_filter() + if self.isVisible() and not self.queue.active and not self._preparing: + self._compatibility_pending = True + self._compatibility_timer.start() + self._invalidate_preview() + self._refresh() + if self.isVisible(): + self._fetch_versions() + + def _check_compatibility(self): + if self._closed or self.queue.active or self._preparing: + return + revision = self._compatibility_revision + product = self.product + paths = [ + self._choice_executable(combo, index) + for combo in (self.python_select, self.environment_select) + for index in range(combo.count()) + ] + managed = ( + self.environment + if not self._custom_environment() + else self.directory / "environments" / product.key + ) + if python_executable(managed).is_file(): + paths.append(str(python_executable(managed))) + offline = self.source.currentData() == "offline" + options = dict( + version=self._version(), + source="release" if offline else self.source.currentData(), + branch=self.branch.text().strip(), + wheelhouse=self.wheelhouse_path.text().strip() if offline else None, + probes=dict(self._probe_cache), + ) + if offline and not options["wheelhouse"]: + self._compatibility_pending = False + self._compatibility_error = ( + "Choose a wheelhouse to check its Python requirements." + ) + self._refresh() + return + + def check(): + try: + return revision, check_compatibility(product, paths, **options), "" + except Exception as error: + return revision, None, str(error) + + self._background(check, self._compatibility_checked) + + @QtCore.Slot(object, object) + def _compatibility_checked(self, payload, error): + if self._closed: + return + if error or payload is None: + return + revision, result, error = payload + if revision != self._compatibility_revision: + return + self._compatibility_pending = False + self._compatibility_error = error + self._compatibility = result + self.python_hint.setToolTip(error) + if error: + self._append_log(self.product.key, f"Compatibility check: {error}\n") + if result is not None: + self._probe_cache = result.probes + for combo in (self.python_select, self.environment_select): + for index in range(combo.count()): + executable = self._choice_executable(combo, index) + self._set_choice_enabled( + combo, + index, + executable in result.interpreters, + result.errors.get( + executable, "No Python interpreter was found." + ), + ) + self._choose_supported_python() + self._refresh() + + def _python_selection_state(self): + try: + root = self.environment + except ValueError: + return ( + False, + "Select an available environment, or create one in Create virtual environments.", + ) + existing = python_executable(root) + executable = ( + str(existing) + if self._custom_environment() or existing.is_file() + else self._base_python() + ) + if self._compatibility_pending: + return False, "Checking the selected release and installed Python versions…" + if self._compatibility_error: + if ( + self.source.currentData() == "offline" + and not self.wheelhouse_path.text().strip() + ): + return False, "Choose a wheelhouse to check its Python requirements." + return ( + bool(executable), + "Release requirements could not be checked. Install retries before making changes; see the activity log for details.", + ) + if self._compatibility is not None: + release = self._compatibility.release + required = str( + SpecifierSet(release.requires_python) + & SpecifierSet(self.product.python) + ) + info = self._compatibility.interpreters.get(executable) + manual = ( + not self._custom_environment() + and self._base_python() in self._manual_pythons + ) + if manual: + required = release.requires_python + probe = self._compatibility.probes.get(executable) + if ( + probe + and probe[1].bits == 64 + and Version(probe[1].version) in SpecifierSet(required) + ): + return ( + True, + f"Manual Python {probe[1].version}. This release requires Python {self._readable_python(required)}; package dependencies are checked during installation.", + ) + if info is not None: + if existing.is_file() and not self._custom_environment(): + return True, f"{release.version} requires 64-bit Python {required}." + prefix = ( + "Dedicated environment uses" + if existing.is_file() and not self._custom_environment() + else "Selected" + ) + return ( + True, + f"{prefix} Python {info.version} (64-bit). {release.version} requires Python {required}.", + ) + if existing.is_file() and not self._custom_environment(): + return ( + False, + f"This dedicated environment is incompatible with {release.version}. Choose an existing environment with Python {required}, or create one in Create virtual environments.", + ) + return ( + False, + f"{release.version} requires 64-bit Python {required}. Select a supported Python or environment.", + ) + if not executable: + return ( + False, + f"Install 64-bit Python {self.product.python} in Install Python, then refresh the choices here.", + ) + return ( + True, + f"Requires 64-bit Python {self.product.python}. The selected release is checked before installation.", + ) + + @staticmethod + def _readable_python(specification): + bounds = list(SpecifierSet(specification)) + if all(bound.operator in (">=", ">", "<=", "<") for bound in bounds): + lower = [bound for bound in bounds if bound.operator.startswith(">")] + upper = [bound for bound in bounds if bound.operator.startswith("<")] + selected = ( + [max(lower, key=lambda bound: Version(bound.version))] if lower else [] + ) + ( + [min(upper, key=lambda bound: Version(bound.version))] if upper else [] + ) + return ", ".join( + str(bound) + .replace(">=", "≥ ") + .replace("<=", "≤ ") + .replace("<", "< ") + .replace(">", "> ") + for bound in selected + ) + return specification + + def _refresh(self): + product = self.product + server = self.servers[product.key] + busy = self.queue.active or self._preparing + environment_busy, installed, managed_exists = False, False, False + try: + root = self.environment + environment_busy = self.environment_in_use(root) + version = installed_version(root, product) + installed = console_executable(root, product).is_file() and bool(version) + managed_exists = ( + not self._custom_environment() and python_executable(root).is_file() + ) + self.installed_label.setText( + f"Installed · {version}" if installed else "Not installed" + ) + self.location_details.setText( + f"Environment: {root}\nPython: {python_executable(root) if managed_exists else self._base_python()}" + ) + except (ValueError, OSError) as error: + self.installed_label.setText("Not installed") + self.location_details.setText(str(error)) + compatible, hint = self._python_selection_state() + for spec in sorted( + { + str(SpecifierSet(self.product.python)), + ( + str( + SpecifierSet(self._compatibility.release.requires_python) + & SpecifierSet(self.product.python) + ) + if self._compatibility + else "" + ), + }, + key=len, + reverse=True, + ): + if spec: + hint = hint.replace(spec, self._readable_python(spec)) + self.python_hint.setText(hint) + required = self.product.python + release_name = "" + if self._compatibility is not None: + release = self._compatibility.release + required = str( + SpecifierSet(required) & SpecifierSet(release.requires_python) + ) + if ( + not self._custom_environment() + and self._base_python() in self._manual_pythons + ): + required = release.requires_python + release_name = f" · MCP {release.version}" + self.python_support.setText( + f"{self._readable_python(required)} · 64-bit{release_name}" + ) + self.python_hint.setVisible( + not compatible + or self._compatibility_pending + or bool(self._compatibility_error) + or ( + not self._custom_environment() + and self._base_python() in self._manual_pythons + ) + ) + self.product_select.setEnabled(not busy) + self.install_options.setEnabled(not busy and not server.active) + self.install_button.setText("Update / repair" if installed else "Install MCP") + self.install_button.setEnabled(not busy and not environment_busy and compatible) + self.cancel_button.setVisible(busy) + self.cancel_button.setEnabled(busy) + self.save_button.setEnabled(not busy) + self.server_save_button.setEnabled(not busy) + self.progress.setVisible(busy) + self.managed_panel.setVisible(not self._custom_environment()) + self.existing_panel.setVisible(self._custom_environment()) + self.python_select.setEnabled(True) + self.python_select.setVisible(True) + self.python_caption.setText("Select Python version") + self.managed_python_info.setVisible(managed_exists) + if managed_exists: + probe = self._probe_cache.get(str(python_executable(root))) + self.managed_python_info.setText( + f"Python {probe[1].version} ({probe[1].bits}-bit) · existing dedicated environment" + if probe + else "Checking the existing environment…" + ) + source = self.source.currentData() + self.package_form.setRowVisible(self.version_row, source != "branch") + self.package_form.setRowVisible(self.branch, source == "branch") + self.package_form.setRowVisible(self.wheelhouse_row, source == "offline") + self.source_hint.setText( + { + "release": "Latest checks PyPI again when you install.", + "branch": "Uses the selected branch, tag or commit from the official repository. Git is required.", + "offline": "Latest uses the newest stable MCP wheel in this folder or ZIP. No network is used.", + }[source] + ) + self.server_options.setEnabled(not busy) + self.http_port.setEnabled(not server.active) + self.solver_section.setEnabled(not server.active) + self.server_advanced_toggle.setEnabled(not server.active) + self.server_advanced.setEnabled(not server.active) + self.http_section.setVisible(product.http_flags is not None) + self.stdio_notice.setVisible(product.http_flags is None) + self.solver_section.setVisible(bool(product.connect_flag)) + self.solver_fields.setVisible(self.connect.isChecked()) + self.aedt_section.setVisible(product.key == "pyaedt") + self.start_button.setVisible(product.http_flags is not None) + self.stop_button.setVisible(product.http_flags is not None) + self.start_button.setEnabled( + installed + and product.http_flags is not None + and not server.active + and not busy + ) + self.stop_button.setEnabled(server.active) + self.endpoint.setText(f"http://127.0.0.1:{self.http_port.value()}/mcp") + self.server_status.setText( + ( + server.state + if installed or server.active + else "Install this MCP in Installation before starting a server." + ) + if product.http_flags + else "Automatic connection: the coding agent starts this server." + ) + self.write_profile_button.setEnabled(installed and not busy) + self.write_profile_button.setToolTip( + "Review the configuration before saving it." + if self._profile_preview is None + else "Save the reviewed configuration and create a backup." + ) + + def _browse_python(self): + filename, _ = QtWidgets.QFileDialog.getOpenFileName( + self, "Select a Python executable" + ) + if filename: + self.select_python(filename) + + def _browse_environment(self): + directory = QtWidgets.QFileDialog.getExistingDirectory( + self, "Select an existing virtual or conda environment" + ) + if directory: + self.select_environment(directory) + + def _browse_wheelhouse(self): + filename, _ = QtWidgets.QFileDialog.getOpenFileName( + self, + "Select wheelhouse ZIP (or cancel to choose a directory)", + filter="Wheelhouse (*.zip)", + ) + if not filename: + filename = QtWidgets.QFileDialog.getExistingDirectory( + self, "Select wheel directory" + ) + if filename: + self.wheelhouse_path.setText(filename) + + def _background(self, function, complete): + task = _Task(function) + self._tasks.append(task) + task.signals.completed.connect(complete) + task.signals.finished.connect(self._task_finished) + QtCore.QThreadPool.globalInstance().start(task) + + @QtCore.Slot(object) + def _task_finished(self, task): + if task in self._tasks: + self._tasks.remove(task) + + def _fetch_versions(self): + if self._closed or self.source.currentData() == "branch": + return + product = self.product + key = self._version_key() + if key is None: + self._set_versions([]) + return + wheelhouse = ( + self.wheelhouse_path.text().strip() + if self.source.currentData() == "offline" + else None + ) + cached = self._versions.get(key) + if cached: + self._set_versions(cached[1]) + if time.monotonic() - cached[0] < 900: + return + if key in self._version_pending: + return + self._version_pending.add(key) + self.version.setToolTip("Loading releases… Latest is always available.") + + def fetch(): + try: + return ( + key, + ( + available_versions(product, wheelhouse=wheelhouse) + if wheelhouse + else available_versions(product) + ), + None, + ) + except Exception as error: + return key, [], str(error) + + self._background(fetch, self._versions_fetched) + + def _set_versions(self, versions): + selected = self._version() + with QtCore.QSignalBlocker(self.version): + self.version.clear() + self.version.addItem("Latest", "") + self.version.addItems(versions) + if selected: + self.version.setCurrentText(selected) + + def _version_key(self): + if self.source.currentData() != "offline": + return self.product.key + path = Path(self.wheelhouse_path.text().strip()) + if not self.wheelhouse_path.text().strip() or not path.exists(): + return None + return (self.product.key, str(path.absolute()), path.stat().st_mtime_ns) + + @QtCore.Slot(object, object) + def _versions_fetched(self, result, error): + if self._closed: + return + # Each request carries its product key; product switches cannot mislabel releases. + key, versions, error = result + self._version_pending.discard(key) + if error: + if self._version_key() == key: + self.version.setToolTip( + "Releases could not be loaded. Use Latest; opening this list retries." + ) + return + self._versions[key] = (time.monotonic(), versions) + if self._version_key() == key and self.source.currentData() != "branch": + previous = self._version() + self._set_versions(versions) + if previous != self._version(): + self._requirements_changed() + self.version.setToolTip("Latest is resolved again on every installation.") + + def _install(self, upgrade, validate_only=False): + if self.queue.active or self._preparing: + raise ValueError("Wait for the current installation to finish.") + if self.environment_in_use(self.environment): + raise ValueError("Stop the server before modifying its environment.") + offline = self.source.currentData() == "offline" + source = "release" if offline else self.source.currentData() + version = self._version() + branch = self.branch.text().strip() + package_requirement(self.product, source, version, branch) + self._save(announce=False) + self._install_product = self.product + self._install_root = self.environment + self._install_custom = self._custom_environment() + self._validate_only = validate_only + options = dict( + version=version, + source=source, + branch=branch, + custom=self._install_custom, + upgrade=upgrade, + allow_fallback=False, + enforce_catalog_python=self._custom_environment() + or self._base_python() not in self._manual_pythons, + ) + if offline: + source_path = self.wheelhouse_path.text().strip() + if not source_path: + raise ValueError("Choose an offline wheelhouse directory or ZIP.") + self._wheelhouse = tempfile.TemporaryDirectory(prefix="pyansys-mcp-wheels-") + options.update( + wheelhouse=source_path, extract_to=Path(self._wheelhouse.name) + ) + product, root, base = ( + self.product, + self._install_root, + self._base_python(), + ) + self._compatibility_timer.stop() + self._compatibility_revision += 1 + self._compatibility_pending = False + self._preparing = True + self._prepare_cancelled = False + self.status.setText("Checking the selected release and supported Python…") + self._refresh() + self._background( + lambda: prepare_installation(product, root, base, **options), + self._installation_prepared, + ) + + @QtCore.Slot(object, object) + def _installation_prepared(self, plan, error): + self._preparing = False + if self._closed or self._prepare_cancelled: + self._cleanup_wheelhouse() + if not self._closed: + self.status.setText("Preparation cancelled.") + self._refresh() + return + if error: + self._error(error) + self._cleanup_wheelhouse() + self._refresh() + return + self._try(lambda: self._begin_install(plan)) + + def _begin_install(self, plan): + try: + self._install_release = plan.release + if plan.creating_environment and not self._install_custom: + with QtCore.QSignalBlocker(self.python_select): + self._select_path(self.python_select, plan.interpreter.executable) + details = ( + f"Selected {self.product.name} {plan.release.version}; release requires Python " + f"{plan.release.requires_python}; using Python {plan.interpreter.version} (64-bit)." + ) + self.python_hint.setText(details) + self._append_log(self.product.key, details + "\n") + self._save(announce=False) + if self._validate_only: + self.status.setText(details) + self._cleanup_wheelhouse() + return + # Ensure the parent exists; venv itself creates the environment only + # after the interpreter preflight succeeds. + self._install_root.parent.mkdir(parents=True, exist_ok=True) + self.status.setText( + f"Installing {self.product.name} {plan.release.version}…" + ) + self.queue.start(plan.commands) + except Exception: + self._cleanup_wheelhouse() + raise + finally: + self._refresh() + + @QtCore.Slot(bool, str) + def _installed(self, success, message): + self._cleanup_wheelhouse() + if ( + success + and not console_executable( + self._install_root, self._install_product + ).is_file() + ): + success = False + message = "Package command was not found after installation. See the log." + if success and not self._install_release.version.startswith("Git:"): + actual = installed_version(self._install_root, self._install_product) + if actual != self._install_release.version: + success = False + message = f"Expected {self._install_release.version}, but found {actual}. Installation was not verified." + else: + message = f"Installation completed: {self._install_product.name} {actual}; dependencies checked." + self.status.setText(message) + if not success: + self._error(message) + self._refresh() + parent = self._manager + if success and parent is not None and hasattr(parent, "installed_table_tab"): + parent.installed_table_tab.update_table() + if success: + self._refresh_choices() + + def _cleanup_wheelhouse(self): + if self._wheelhouse is not None: + self._wheelhouse.cleanup() + self._wheelhouse = None + + def _cancel_install(self): + if self._preparing: + self._prepare_cancelled = True + self.status.setText("Cancelling installation preflight…") + # The background extractor owns this directory until its callback. + self._refresh() + self.queue.cancel() + + def _arguments(self, transport): + extra = json.loads(self.extra.toPlainText()) + if not isinstance(extra, list) or any( + not isinstance(value, str) or "\0" in value for value in extra + ): + raise ValueError( + "Extra arguments must be a JSON array of strings without null characters." + ) + product = self.product + if self._launch_values and self._launch_context != self._launch_signature(): + self._load_launch_options() + raise ValueError( + "Launch options are being checked for this installation. Please try again when they finish loading." + ) + arguments = option_arguments(self._launch_schema, self._launch_values) + if product.connect_flag and self.connect.isChecked(): + arguments.extend( + [ + product.connect_flag, + product.machine_flag, + self.machine.text().strip() or "127.0.0.1", + "--port", + str(self.solver_port.value()), + ] + ) + if product.key == "pyaedt": + for field, flag in ( + (self.graphical, "--graphical"), + (self.context, "--include-context"), + (self.dynamic, "--dynamic-tool-discovery"), + ): + if field.isChecked(): + arguments.append(flag) + return server_arguments( + product, transport, self.http_port.value(), [*arguments, *extra] + ) + + def _launch_signature(self): + try: + return ( + self.product.key, + str(self.environment), + installed_version(self.environment, self.product), + ) + except (ValueError, OSError): + return None + + def _load_launch_options(self): + signature = self._launch_signature() + if not signature or not signature[2]: + self.launch_hint.setText( + "Install this MCP to see its supported launch options." + ) + return + if signature == self._launch_context or signature in self._launch_pending: + return + self._launch_context = None + self._launch_schema = [] + self.launch_choice.setEnabled(False) + self.launch_hint.setText("Reading options from the installed MCP…") + self._launch_pending.add(signature) + product, root = self.product, self.environment + + def inspect(): + try: + return signature, launch_options(root, product), None + except Exception as error: + return signature, [], str(error) + + self._background(inspect, self._launch_loaded) + + @QtCore.Slot(object, object) + def _launch_loaded(self, result, error): + if self._closed: + return + signature, schema, error = result + self._launch_pending.discard(signature) + if signature != self._launch_signature(): + return + if error: + self.launch_hint.setText( + f"{error} Custom arguments remain available below." + ) + return + self._launch_context = signature + # These options already have dedicated, validated controls in APM. + managed = { + "--transport", + "--http-host", + "--http-port", + "--host", + "--connect", + "--connect-on-startup", + "--machine", + "--ip", + "--port", + "--graphical", + "--non-graphical", + "--include-context", + "--dynamic-tool-discovery", + } + self._launch_schema = [ + option for option in schema if not managed.intersection(option["flags"]) + ] + self.launch_hint.setText( + f"Options for installed release {signature[2]}. Transport and connection settings are managed above." + if schema + else "This MCP has no command-line launch options. Environment variables can be set below." + ) + self._render_launch_options() + + def _render_launch_options(self): + while self.launch_rows.count(): + item = self.launch_rows.takeAt(0) + item.widget().deleteLater() + with QtCore.QSignalBlocker(self.launch_choice): + self.launch_choice.clear() + self.launch_choice.addItem("Add an option…", None) + for option in self._launch_schema: + flag = option["flags"][0] + if flag not in self._launch_values: + self.launch_choice.addItem( + flag.removeprefix("--").replace("-", " ").capitalize(), flag + ) + self.launch_choice.setItemData( + self.launch_choice.count() - 1, + option["help"], + QtCore.Qt.ToolTipRole, + ) + self.launch_choice.setEnabled(bool(self._launch_schema)) + schema = {option["flags"][0]: option for option in self._launch_schema} + for flag, value in self._launch_values.items(): + row = QtWidgets.QWidget() + layout = QtWidgets.QHBoxLayout(row) + layout.setContentsMargins(0, 0, 0, 0) + label = self._label(flag) + layout.addWidget(label) + option = schema.get(flag) + if not option: + layout.addWidget(self._label("Awaiting validation for this release"), 1) + elif option["kind"] == "flag": + layout.addWidget(self._label("Enabled"), 1) + else: + if option["choices"]: + editor = self._compact_combo(QtWidgets.QComboBox()) + editor.addItems([str(choice) for choice in option["choices"]]) + editor.setCurrentText(str(value)) + editor.currentTextChanged.connect( + lambda text, flag=flag: self._set_launch_value(flag, text) + ) + else: + editor = QtWidgets.QLineEdit( + json.dumps(value) if isinstance(value, list) else str(value) + ) + editor.setPlaceholderText( + 'JSON array, e.g. ["value"]' + if option["nargs"] in ("+", "*") + or (type(option["nargs"]) is int and option["nargs"] > 0) + else "Value" + ) + editor.textChanged.connect( + lambda text, flag=flag, option=option: self._edit_launch_value( + flag, text, option + ) + ) + editor.setAccessibleName(flag) + editor.setToolTip(option["help"] + f"\nDefault: {option['default']}") + layout.addWidget(editor, 1) + layout.addWidget( + self._button( + "Remove", lambda flag=flag: self._remove_launch_option(flag) + ) + ) + self.launch_rows.addWidget(row) + + def _add_launch_option(self, index): + flag = self.launch_choice.itemData(index) + if not flag: + return + option = next( + option for option in self._launch_schema if option["flags"][0] == flag + ) + self._launch_values[flag] = ( + True if option["kind"] == "flag" else str(option["default"] or "") + ) + if option["nargs"] in ("+", "*") or ( + type(option["nargs"]) is int and option["nargs"] > 0 + ): + self._launch_values[flag] = [] + self._render_launch_options() + self._launch_options_changed() + + def _set_launch_value(self, flag, value): + self._launch_values[flag] = value + self._launch_options_changed() + + def _edit_launch_value(self, flag, text, option): + value = text + if option["nargs"] in ("+", "*") or ( + type(option["nargs"]) is int and option["nargs"] > 0 + ): + try: + value = json.loads(text) + except ValueError: + value = None + self._set_launch_value(flag, value) + + def _remove_launch_option(self, flag): + self._launch_values.pop(flag, None) + self._render_launch_options() + self._launch_options_changed() + + def _environment_variables(self): + values = json.loads(self.environment_json.toPlainText()) + if not isinstance(values, dict) or any( + not isinstance(key, str) + or not key + or "=" in key + or "\0" in key + or not isinstance(value, str) + or "\0" in value + for key, value in values.items() + ): + raise ValueError( + "Environment variables must be a JSON object of string names and values." + ) + return values + + def _start_server(self): + arguments = self._arguments("http") + environment = self._environment_variables() + root = self.environment + executable = console_executable(root, self.product) + if not executable.is_file(): + raise ValueError("Install this MCP before starting its server.") + self._save(announce=False) + self.servers[self.product.key].environment_root = root + self.servers[self.product.key].start( + executable, arguments, self.http_port.value(), environment + ) + self._refresh() + + def environment_in_use(self, directory): + """Protect an environment from deletion or mutation while the manager uses it.""" + root = Path(directory).resolve() + if (self.queue.active or self._preparing) and hasattr(self, "_install_root"): + if self._install_root.resolve() == root: + return True + return any( + server.active + and getattr(server, "environment_root", None) is not None + and server.environment_root.resolve() == root + for server in self.servers.values() + ) + + def _server_changed(self, key): + if key == self.product.key: + self._refresh() + + def _transport(self): + return self.transport.currentData() or "stdio" + + def _update_transports(self, preferred=None): + selected = preferred or self._transport() + with QtCore.QSignalBlocker(self.transport): + self.transport.clear() + self.transport.addItem("Automatic (stdio)", "stdio") + if ( + self.product.http_flags + and self.client.currentText() != "Claude Desktop" + ): + self.transport.addItem("Shared HTTP server", "http") + index = self.transport.findData(selected) + self.transport.setCurrentIndex(index if index >= 0 else 0) + self._connection_changed() + + def _client_changed(self): + client = self.client.currentText() + self.vscode_controls.setVisible(client == "VS Code") + self.vscode_format.setVisible(client == "VS Code") + self.workspace_button.setVisible(client == "VS Code") + self._vscode_format_changed() + self._update_transports() + + def _vscode_format_changed(self, *_): + if self.client.currentText() == "VS Code" and self.vscode_format.currentData(): + config = ( + Path(os.environ.get("APPDATA") or Path.home() / "AppData/Roaming") + if os.name == "nt" + else Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") + ) + path = config / "Code/User/mcp.json" + else: + path = default_profile_path(self.client.currentText()) + self.profile_path.setText(str(path)) + self._connection_changed() + + def _connection_changed(self, *_): + self.client_hint.setText( + f"Start the HTTP server in Server settings before using this agent. APM must stay open." + if self._transport() == "http" + else "Your coding agent starts this MCP automatically. APM can be closed afterward." + ) + self.profile_hint.setText( + ( + "Legacy VS Code user profile. Choose workspace for a project setup. Existing settings are preserved and backed up." + if self.vscode_format.currentData() + else "Personal Copilot configuration, shared with Copilot CLI. Choose workspace for a project setup. Existing settings are preserved and backed up." + ) + if self.client.currentText() == "VS Code" + else "Existing settings are preserved. A backup is saved before updating the file." + ) + self._invalidate_preview() + + def _launch_options_changed(self, *_): + configured = ( + bool(self._launch_values) + or any( + field.isChecked() + for field in (self.graphical, self.context, self.dynamic) + ) + or self.extra.toPlainText().strip() not in ("", "[]") + or self.environment_json.toPlainText().strip() not in ("", "{}") + ) + self.server_advanced_toggle.setText( + "Advanced launch settings · customized" + if configured + else "Advanced launch settings" + ) + self._invalidate_preview() + + def _browse_workspace(self): + directory = QtWidgets.QFileDialog.getExistingDirectory( + self, "Select a VS Code workspace folder" + ) + if directory: + relative = ( + ".vscode/mcp.json" if self.vscode_format.currentData() else ".mcp.json" + ) + self.profile_path.setText(str(Path(directory) / relative)) + + def _browse_profile(self): + filename, _ = QtWidgets.QFileDialog.getSaveFileName( + self, "Choose the coding agent configuration file", self.profile_path.text() + ) + if filename: + self.profile_path.setText(filename) + + def _invalidate_preview(self, *_): + self._profile_preview = None + self.preview.clear() + self.preview_section.hide() + self.write_profile_button.setText("Review configuration…") + if ( + hasattr(self, "status") + and self.status.text() == "Review the changes, then save the configuration." + ): + self.status.clear() + + def _preview_profile(self): + if self.queue.active or self._preparing: + raise ValueError( + "Wait for installation to finish before configuring a client." + ) + executable = console_executable(self.environment, self.product) + if not executable.is_file(): + raise ValueError("Install this MCP before configuring a client.") + if not self.profile_path.text().strip(): + raise ValueError("Choose a client configuration file.") + path = Path(self.profile_path.text()).expanduser().absolute() + original = path.read_text(encoding="utf-8") if path.exists() else "" + transport = self._transport() + arguments = self._arguments("stdio") + rendered = render_profile( + self.client.currentText(), + original, + self.product, + executable, + arguments, + transport=transport, + port=self.http_port.value(), + vscode_legacy=bool(self.vscode_format.currentData()), + environment=self._environment_variables(), + ) + self.preview.setPlainText(rendered) + self.preview_section.show() + self._profile_preview = (path, original, rendered) + self.write_profile_button.setEnabled(True) + self.write_profile_button.setText("Save reviewed configuration") + self.status.setText("Review the changes, then save the configuration.") + + def _review_or_write_profile(self): + if self._profile_preview is None: + self._preview_profile() + else: + self._write_profile() + + def _write_profile(self): + if self._profile_preview is None: + raise ValueError("Preview the profile before installing it.") + path, original, rendered = self._profile_preview + backup = save_profile(path, original, rendered) + self.status.setText( + f"Profile saved to {path}. Reload the client." + + (f" Backup: {backup}" if backup else "") + ) + self._profile_preview = None + self.write_profile_button.setText("Review configuration…") + + def shutdown(self, save_settings=True): + """Stop owned processes and persist the selected product's settings.""" + if self._closed: + return + self._closed = True + self._compatibility_timer.stop() + self._compatibility_revision += 1 + if save_settings: + self._try(lambda: self._save(announce=False)) + self.queue.shutdown() + for server in self.servers.values(): + server.shutdown() + if not self._preparing: + self._cleanup_wheelhouse() diff --git a/src/ansys/tools/installer/uninstall.py b/src/ansys/tools/installer/uninstall.py index a40ace5a..1da20bb9 100644 --- a/src/ansys/tools/installer/uninstall.py +++ b/src/ansys/tools/installer/uninstall.py @@ -23,6 +23,7 @@ """Uninstall application.""" import os +from pathlib import Path import shutil from PySide6 import QtCore, QtGui, QtWidgets @@ -36,6 +37,7 @@ get_os_version, is_linux_os, ) +from ansys.tools.installer.mcp_backend import application_directory class Uninstall(QtWidgets.QWidget): @@ -181,6 +183,10 @@ def __init__(self, parent): def _uninstall(self): """Uninstallation function. Execute the uninstaller script.""" + if hasattr(self._parent, "mcp_tab"): + self._parent.mcp_tab.shutdown( + save_settings=not self.uninstall_window_cache_remove_configs_checkbox.isChecked() + ) if self.uninstall_window_cache_remove_venv_checkbox.isChecked(): self._remove_all_venvs() @@ -218,7 +224,13 @@ def _remove_all_venvs(self): try: configure = ConfigureJson() script_path = "bin" if is_linux_os() else "Scripts" - for venv_dir in configure.history["path"]: + search_paths = [ + *configure.history["path"], + str(application_directory() / "environments"), + ] + for venv_dir in dict.fromkeys(search_paths): + if not os.path.isdir(venv_dir): + continue for venv_dir_name in os.listdir(venv_dir): if os.path.isfile( os.path.join(venv_dir, venv_dir_name, script_path, "activate") @@ -241,8 +253,18 @@ def _remove_configs(self): """Remove all the configurations created by Ansys Python Manager.""" try: configure = ConfigureJson() - print(f"removed {configure.config_dir}") - shutil.rmtree(configure.config_dir, ignore_errors=True) + # MCP environments are under this directory too. Removing settings + # must not delete environments unless that separate option was chosen. + for filename in ("config.json", "history.json", "mcp/settings.json"): + (Path(configure.config_dir) / filename).unlink(missing_ok=True) + for directory in ( + Path(configure.config_dir) / "mcp", + Path(configure.config_dir), + ): + try: + directory.rmdir() + except OSError: + pass except: pass diff --git a/tests/test_gui.py b/tests/test_gui.py index 125cce3c..4bd47930 100644 --- a/tests/test_gui.py +++ b/tests/test_gui.py @@ -23,11 +23,13 @@ from PySide6 import QtWidgets import pytest +from ansys.tools.installer import mcp_tab from ansys.tools.installer.main import AnsysPythonInstaller @pytest.fixture -def gui(qtbot): +def gui(qtbot, monkeypatch, tmp_path): + monkeypatch.setattr(mcp_tab, "application_directory", lambda: tmp_path / "mcp") installer = AnsysPythonInstaller(show=False) qtbot.addWidget(installer) yield installer diff --git a/tests/test_mcp_backend.py b/tests/test_mcp_backend.py new file mode 100644 index 00000000..7b38bede --- /dev/null +++ b/tests/test_mcp_backend.py @@ -0,0 +1,376 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import json +import subprocess +import sys +from types import MethodType, SimpleNamespace +import zipfile + +import pytest + +from ansys.tools.installer import mcp_backend as backend +from ansys.tools.installer.mcp_catalog import PRODUCT_BY_KEY, PRODUCTS +from ansys.tools.installer.mcp_releases import PythonInfo + + +def test_dedicated_environments_follow_selected_python_without_replacing_others( + tmp_path, +): + first = tmp_path / "python313" / "python.exe" + second = tmp_path / "python314" / "python.exe" + product = PRODUCTS[0] + root = backend.managed_environment(tmp_path, product, first) + interpreter = backend.python_executable(root) + interpreter.parent.mkdir(parents=True) + interpreter.touch() + (root / "pyvenv.cfg").write_text(f"executable = {first}\n", encoding="utf-8") + marker = root / "preserve.txt" + marker.write_text("first environment") + alternate = backend.managed_environment(tmp_path, product, second) + assert alternate != root and alternate.parent == root.parent + assert backend.managed_environment(tmp_path, product, first) == root + assert backend.managed_environment(tmp_path, product, second) == alternate + assert marker.read_text() == "first environment" + # Creating a venv from another venv must not retarget it after installation. + creator = ( + tmp_path + / "creator" + / ("Scripts" if sys.platform == "win32" else "bin") + / "python.exe" + ) + creator.parent.mkdir(parents=True) + (creator.parent.parent / "pyvenv.cfg").write_text( + f"executable = {first}\n", encoding="utf-8" + ) + (root / "pyvenv.cfg").write_text(f"executable = {creator}\n", encoding="utf-8") + assert backend.managed_environment(tmp_path, product, creator) == root + assert backend.managed_environment(tmp_path, product, first) == root + + +def test_manual_python_uses_release_requirements_without_silent_fallback( + tmp_path, monkeypatch +): + from ansys.tools.installer import mcp_releases + from ansys.tools.installer.mcp_releases import ReleaseInfo + + python = tmp_path / "python39.exe" + python.touch() + info = PythonInfo(str(python), "3.9.13", 64) + monkeypatch.setattr(mcp_releases, "inspect_python", lambda path: info) + monkeypatch.setattr( + backend, + "resolve_release", + lambda *a, **k: (ReleaseInfo("old", ">=3.8", "example==1"), None), + ) + monkeypatch.setattr( + backend, + "_installed_pythons", + lambda: pytest.fail("Explicit Python must not be silently replaced"), + ) + with pytest.raises(ValueError, match="requires"): + backend.prepare_installation( + PRODUCTS[0], tmp_path / "target", python, allow_fallback=False + ) + plan = backend.prepare_installation( + PRODUCTS[0], + tmp_path / "target", + python, + allow_fallback=False, + enforce_catalog_python=False, + ) + assert plan.interpreter == info and plan.creating_environment + assert not any("--ignore-requires-python" in command for command in plan.commands) + monkeypatch.setattr( + backend, + "resolve_release", + lambda *a, **k: (ReleaseInfo("new", ">=3.13", "example==2"), None), + ) + with pytest.raises(ValueError, match="requires"): + backend.prepare_installation( + PRODUCTS[0], + tmp_path / "target", + python, + allow_fallback=False, + enforce_catalog_python=False, + ) + + +@pytest.mark.parametrize("product", PRODUCTS, ids=lambda product: product.key) +def test_launch_contract(product): + if product.key == "pylumerical": + assert backend.server_arguments(product) == [] + with pytest.raises(ValueError, match="stdio only"): + backend.server_arguments(product, "http") + else: + assert backend.server_arguments(product) == ["--transport", "stdio"] + host, port = ( + ("--host", "--port") + if product.key in ("pyfluent", "pycfx") + else ("--http-host", "--http-port") + ) + assert backend.server_arguments(product, "http", 9001) == [ + "--transport", + "http", + host, + "127.0.0.1", + port, + "9001", + ] + + +@pytest.mark.parametrize( + "extra", [["--transport=http"], ["--http-port", "9"], ["--host=0.0.0.0"]] +) +def test_transport_cannot_be_overridden(extra): + with pytest.raises(ValueError): + backend.server_arguments(PRODUCT_BY_KEY["pyfluent"], extra=extra) + + +def test_solver_port_is_distinct_from_http_port(): + args = backend.server_arguments(PRODUCTS[0], "http", 8080, ["--port", "50051"]) + assert args[-2:] == ["--port", "50051"] + assert args[args.index("--http-port") + 1] == "8080" + + +def test_requirement_rejects_injection_and_preserves_branch(): + product = PRODUCTS[0] + assert ( + backend.package_requirement(product, version="0.2.0") == "ansys-aedt-mcp==0.2.0" + ) + assert backend.package_requirement( + product, "branch", branch="feature/new-ui" + ).endswith("https://github.com/ansys/pyaedt-mcp.git@feature/new-ui") + for branch in ("main#egg=other", "--help", "main; calc", "main@evil", ""): + with pytest.raises(ValueError): + backend.package_requirement(product, "branch", branch=branch) + with pytest.raises(ValueError): + backend.package_requirement(product, version="1 --extra-index-url http://evil") + + +def test_install_plan_targets_environment_and_checks_dependencies( + tmp_path, monkeypatch +): + monkeypatch.setattr( + backend, "inspect_python", lambda path: PythonInfo(str(path), "3.13.1", 64) + ) + root = tmp_path / "env with spaces" + commands = backend.installation_commands( + PRODUCTS[1], root, sys.executable, "ansys-mechanical-mcp", upgrade=True + ) + assert not root.exists() + assert commands[1] == [sys.executable, "-I", "-m", "venv", str(root)] + assert commands[-2][0] == str(backend.python_executable(root)) + assert "--upgrade" in commands[-2] + assert commands[-1][-2:] == ["pip", "check"] + probe = subprocess.run(commands[0], capture_output=True) + assert (probe.returncode == 0) == (sys.version_info[:3] == (3, 13, 1)) + + +def test_install_rejects_non_environment_even_when_python_present(tmp_path): + root = tmp_path / "system" + root.mkdir() + python = backend.python_executable(root) + python.parent.mkdir(exist_ok=True) + python.touch() + with pytest.raises(ValueError, match="not an environment"): + backend.installation_commands(PRODUCTS[0], root, sys.executable, "pkg") + with pytest.raises(ValueError, match="not a system Python"): + backend.installation_commands( + PRODUCTS[0], root, sys.executable, "pkg", custom=True + ) + + +def test_offline_plan_never_uses_index_or_git(tmp_path, monkeypatch): + monkeypatch.setattr( + backend, "inspect_python", lambda path: PythonInfo(str(path), "3.13.1", 64) + ) + commands = backend.installation_commands( + PRODUCTS[1], + tmp_path / "env", + sys.executable, + "ansys-mechanical-mcp", + offline=tmp_path, + ) + assert commands[-2][-4:] == [ + "--no-index", + "--find-links", + str(tmp_path), + "ansys-mechanical-mcp", + ] + with pytest.raises(ValueError, match="not Git"): + backend.installation_commands( + PRODUCTS[1], + tmp_path / "env", + sys.executable, + "pkg @ git+https://github.com/ansys/pkg", + offline=tmp_path, + ) + + +@pytest.mark.parametrize("filename", ["../escape.whl", "/escape.whl", "..\\escape.whl"]) +def test_unsafe_zip_rejected_before_extraction(tmp_path, filename): + archive = tmp_path / "wheels.zip" + with zipfile.ZipFile(archive, "w") as stream: + stream.writestr("good.whl", "ok") + stream.writestr(filename, "bad") + destination = tmp_path / "extracted" + with pytest.raises(ValueError, match="unsafe"): + backend.prepare_wheelhouse(archive, destination) + assert not destination.exists() + + +def test_wheelhouse_and_metadata(tmp_path): + archive = tmp_path / "wheels.zip" + with zipfile.ZipFile(archive, "w") as stream: + stream.writestr("example.whl", "example") + target = backend.prepare_wheelhouse(archive, tmp_path / "wheels") + assert (target / "example.whl").read_text() == "example" + metadata = ( + tmp_path + / "env/lib/python3.13/site-packages/ansys_aedt_mcp-1.0.dist-info/METADATA" + ) + metadata.parent.mkdir(parents=True) + metadata.write_text("Name: ansys-aedt-mcp\nVersion: 1.0\n", encoding="utf-8") + assert backend.installed_version(tmp_path / "env", PRODUCTS[0]) == "1.0" + + +def test_platform_paths_and_symlinks(tmp_path): + assert ( + backend.python_executable(tmp_path, windows=True) + == tmp_path / "Scripts/python.exe" + ) + assert backend.python_executable(tmp_path, windows=False) == tmp_path / "bin/python" + assert ( + backend.console_executable(tmp_path, PRODUCTS[0], windows=True).name + == "ansys-aedt-mcp.exe" + ) + assert ( + backend.console_executable(tmp_path, PRODUCTS[0], windows=False) + == tmp_path / "bin/ansys-aedt-mcp" + ) + + +def test_settings_round_trip_and_corruption(tmp_path): + path = tmp_path / "settings.json" + backend.atomic_write(path, json.dumps({"pyaedt": {"version": "0.2.0"}})) + assert backend.read_settings(path)["pyaedt"]["version"] == "0.2.0" + path.write_text("[]") + with pytest.raises(ValueError): + backend.read_settings(path) + assert path.read_text() == "[]" + + +def test_pypi_versions_exclude_yanked_and_prereleases(monkeypatch): + class Response: + def raise_for_status(self): + pass + + def json(self): + return { + "releases": { + "1.0": [{"yanked": False}], + "2.0": [{"yanked": True}], + "3.0rc1": [{}], + "0.9": [], + "0.8": [{}], + } + } + + def get(url, timeout): + assert url == "https://pypi.org/pypi/ansys-aedt-mcp/json" + assert timeout == 20 + return Response() + + monkeypatch.setattr(backend.requests, "get", get) + assert backend.available_versions(PRODUCTS[0]) == ["1.0", "0.8"] + + +def test_remove_settings_preserves_mcp_environments(monkeypatch, tmp_path): + from ansys.tools.installer import uninstall + + root = tmp_path / "manager" + environment = root / "mcp/environments/pyaedt" + environment.mkdir(parents=True) + marker = environment / "pyvenv.cfg" + marker.write_text("home = example") + for filename in ("config.json", "history.json", "mcp/settings.json"): + (root / filename).write_text("{}") + monkeypatch.setattr( + uninstall, "ConfigureJson", lambda: SimpleNamespace(config_dir=root) + ) + uninstall.Uninstall._remove_configs(SimpleNamespace()) + assert marker.exists() + assert not (root / "mcp/settings.json").exists() + assert not (root / "config.json").exists() + + +def test_remove_managed_environments_includes_mcp_only_when_requested( + monkeypatch, tmp_path +): + from ansys.tools.installer import uninstall + + mcp = tmp_path / "mcp" + environment = mcp / "environments/pyaedt" + (environment / "bin").mkdir(parents=True) + (environment / "bin/activate").touch() + external = tmp_path / "external environment" + external.mkdir() + monkeypatch.setattr( + uninstall, + "ConfigureJson", + lambda: SimpleNamespace(history={"path": [str(tmp_path / "missing")]}), + ) + monkeypatch.setattr(uninstall, "application_directory", lambda: mcp) + monkeypatch.setattr(uninstall, "is_linux_os", lambda: True) + uninstall.Uninstall._remove_all_venvs(SimpleNamespace()) + assert not environment.exists() + assert external.exists() + + +def test_existing_package_manager_cannot_mutate_busy_mcp_environment( + tmp_path, monkeypatch +): + from ansys.tools.installer import installed_table + + root = tmp_path / "busy MCP environment" + errors = [] + parent = SimpleNamespace( + mcp_tab=SimpleNamespace(environment_in_use=lambda path: str(path) == str(root)), + show_error=errors.append, + ) + widget = SimpleNamespace( + _parent=parent, + is_chk_box_active=lambda: False, + venv_table=SimpleNamespace(active_path=str(root / "Scripts")), + ) + widget._mcp_operation_blocks_changes = MethodType( + installed_table.InstalledTab._mcp_operation_blocks_changes, widget + ) + monkeypatch.setattr( + installed_table.subprocess, + "call", + lambda *args, **kwargs: pytest.fail("Must not start a competing installer"), + ) + installed_table.InstalledTab.launch_cmd(widget, "uv pip install numpy") + assert len(errors) == 1 + assert "Stop the MCP server" in errors[0] diff --git a/tests/test_mcp_compatibility.py b/tests/test_mcp_compatibility.py new file mode 100644 index 00000000..754ff574 --- /dev/null +++ b/tests/test_mcp_compatibility.py @@ -0,0 +1,102 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import os +from pathlib import Path + +from ansys.tools.installer import mcp_backend, mcp_compatibility +from ansys.tools.installer.mcp_catalog import PRODUCT_BY_KEY +from ansys.tools.installer.mcp_releases import PythonInfo, ReleaseInfo + + +def test_release_specific_requirements_and_actual_bitness(tmp_path, monkeypatch): + product = PRODUCT_BY_KEY["pymechanical"] + paths = [str(tmp_path / name) for name in ("old", "supported", "32bit")] + for path in paths: + Path(path).touch() + monkeypatch.setattr( + mcp_backend, + "published_release", + lambda *args: ReleaseInfo("2.0", ">=3.12.9,<3.14", product.package + "==2.0"), + ) + monkeypatch.setattr( + mcp_compatibility, + "inspect_python", + lambda path: PythonInfo( + path, + "3.12.8" if path == paths[0] else "3.13.1", + 32 if path == paths[2] else 64, + ), + ) + result = mcp_compatibility.check_compatibility(product, paths) + assert list(result.interpreters) == [paths[1]] + assert "3.12.8" in result.errors[paths[0]] + assert "32-bit" in result.errors[paths[2]] + assert result.release.version == "2.0" + + +def test_interpreter_cache_does_not_cache_latest_release(tmp_path, monkeypatch): + product = PRODUCT_BY_KEY["pymechanical"] + path = tmp_path / "python" + path.touch() + calls, probes = [], [] + + def release(*args): + calls.append(True) + return ReleaseInfo(str(len(calls)), ">=3.12", product.package) + + def inspect(executable): + probes.append(executable) + return PythonInfo(executable, "3.13.1", 64) + + monkeypatch.setattr(mcp_backend, "published_release", release) + monkeypatch.setattr(mcp_compatibility, "inspect_python", inspect) + first = mcp_compatibility.check_compatibility(product, [str(path)]) + second = mcp_compatibility.check_compatibility( + product, [str(path)], probes=first.probes + ) + assert len(calls) == 2 and len(probes) == 1 + assert first.release.version != second.release.version + previous = path.stat() + path.write_text("changed executable") + # A replacement can retain its timestamp, including on coarse filesystems. + os.utime(path, ns=(previous.st_atime_ns, previous.st_mtime_ns)) + mcp_compatibility.check_compatibility(product, [str(path)], probes=second.probes) + assert len(probes) == 2 + + +def test_unreadable_candidate_does_not_hide_supported_candidates(tmp_path, monkeypatch): + product = PRODUCT_BY_KEY["pymechanical"] + good = tmp_path / "good" + good.touch() + missing = tmp_path / "missing" + monkeypatch.setattr( + mcp_backend, + "published_release", + lambda *args: ReleaseInfo("1", ">=3.12", product.package), + ) + monkeypatch.setattr( + mcp_compatibility, "inspect_python", lambda path: PythonInfo(path, "3.13.1", 64) + ) + result = mcp_compatibility.check_compatibility(product, [str(missing), str(good)]) + assert str(good) in result.interpreters + assert str(missing) in result.errors diff --git a/tests/test_mcp_launch.py b/tests/test_mcp_launch.py new file mode 100644 index 00000000..5ae4b716 --- /dev/null +++ b/tests/test_mcp_launch.py @@ -0,0 +1,94 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Validate installed-parser discovery and typed launch arguments.""" + +from dataclasses import replace +from pathlib import Path +import subprocess +import sys + +import pytest + +from ansys.tools.installer.mcp_catalog import PRODUCTS +from ansys.tools.installer.mcp_launch import launch_options, option_arguments + + +def test_inspection_exits_before_server_or_solver_start(tmp_path): + root = tmp_path / "environment with spaces" + subprocess.run( + [sys.executable, "-m", "venv", "--without-pip", str(root)], check=True + ) + site = root / ( + "Lib/site-packages" + if sys.platform == "win32" + else f"lib/python{sys.version_info.major}.{sys.version_info.minor}/site-packages" + ) + site.mkdir(parents=True, exist_ok=True) + metadata = site / "fixture_mcp-1.0.dist-info" + metadata.mkdir() + (metadata / "METADATA").write_text( + "Metadata-Version: 2.1\nName: fixture-mcp\nVersion: 1.0\n", encoding="utf-8" + ) + (metadata / "entry_points.txt").write_text( + "[console_scripts]\nfixture-mcp = fixture_mcp:main\n", encoding="utf-8" + ) + marker = tmp_path / "server-started" + (site / "fixture_mcp.py").write_text( + "import argparse\nfrom pathlib import Path\n" + "def main():\n" + " parser = argparse.ArgumentParser()\n" + " parser.add_argument('--mode', choices=['one', 'two'], default='one')\n" + " parser.add_argument('--origins', nargs='+')\n" + " parser.add_argument('--enabled', action='store_true')\n" + " parser.add_argument('--count', type=int)\n" + " parser.parse_args()\n" + f" Path({str(marker)!r}).touch()\n", + encoding="utf-8", + ) + options = launch_options(root, replace(PRODUCTS[0], package="fixture-mcp")) + assert not marker.exists() + assert len(options) == 4 + assert option_arguments( + options, + {"--mode": "two", "--origins": ["a", "b"], "--enabled": True, "--count": "2"}, + ) == ["--mode", "two", "--origins", "a", "b", "--enabled", "--count", "2"] + for values in ( + {"--unknown": "x"}, + {"--mode": "invalid"}, + {"--count": "abc"}, + {"--origins": []}, + {"--enabled": False}, + ): + with pytest.raises(ValueError): + option_arguments(options, values) + + +def test_lumerical_never_invokes_a_non_argparse_launcher(monkeypatch): + monkeypatch.setattr( + subprocess, + "run", + lambda *a, **k: pytest.fail( + "A stdio-only launcher must not be invoked for --help" + ), + ) + assert launch_options(Path("unused"), PRODUCTS[4]) == [] diff --git a/tests/test_mcp_process.py b/tests/test_mcp_process.py new file mode 100644 index 00000000..705773f7 --- /dev/null +++ b/tests/test_mcp_process.py @@ -0,0 +1,197 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import gc +import socket +import sys + +from PySide6 import QtCore +import pytest + +from ansys.tools.installer.mcp_process import CommandQueue, McpServer + + +def _free_port(): + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + return probe.getsockname()[1] + + +def test_command_queue_is_async_and_stops_on_failure(qtbot, tmp_path): + queue = CommandQueue() + marker = tmp_path / "should not exist" + ticks = [] + QtCore.QTimer.singleShot(20, lambda: ticks.append(True)) + with qtbot.waitSignal(queue.completed, timeout=10000) as completion: + queue.start( + [ + [ + sys.executable, + "-c", + "import time; time.sleep(.15); print('output'); exit(7)", + ], + [sys.executable, "-c", f"open({str(marker)!r}, 'w').close()"], + ] + ) + assert completion.args[0] is False + assert "7" in completion.args[1] + assert ticks + assert not marker.exists() + assert not queue.active + + +def test_command_queue_handles_missing_executable(qtbot, tmp_path): + queue = CommandQueue() + with qtbot.waitSignal(queue.completed, timeout=5000) as completion: + queue.start([[str(tmp_path / "missing-program")]]) + assert completion.args[0] is False + assert not queue.active + + +def test_command_cancel_reaps_process(qtbot): + queue = CommandQueue() + queue.start([[sys.executable, "-c", "import time; time.sleep(60)"]]) + qtbot.waitUntil(lambda: queue.process.state() == QtCore.QProcess.Running) + with qtbot.waitSignal(queue.completed, timeout=5000) as completion: + queue.cancel() + assert completion.args[0] is False + assert "cancelled" in completion.args[1] + assert queue.process.state() == QtCore.QProcess.NotRunning + + +HTTP_FIXTURE = """ +from http.server import BaseHTTPRequestHandler, HTTPServer +import json, sys +class Handler(BaseHTTPRequestHandler): + def do_POST(self): + body = self.rfile.read(int(self.headers['Content-Length'])) + request = json.loads(body) + assert request['method'] == 'initialize' + data = DATA + self.send_response(200) + self.send_header('Content-Type', 'application/json') + self.end_headers() + self.wfile.write(json.dumps(data).encode()) +HTTPServer(('127.0.0.1', int(sys.argv[1])), Handler).serve_forever() +""" + + +@pytest.mark.parametrize("valid", [True, False]) +def test_http_readiness_requires_mcp_handshake(qtbot, valid): + port = _free_port() + data = ( + { + "jsonrpc": "2.0", + "id": 1, + "result": { + "protocolVersion": "2025-03-26", + "capabilities": {}, + "serverInfo": {"name": "fixture", "version": "1"}, + }, + } + if valid + else {"status": "ok"} + ) + script = HTTP_FIXTURE.replace("DATA", repr(data)) + server = McpServer() + try: + server.start(sys.executable, ["-u", "-c", script, str(port)], port) + if valid: + qtbot.waitUntil(lambda: server.state.startswith("Ready:"), timeout=10000) + else: + qtbot.wait(1600) + assert server.active + assert server.state.startswith("Starting") + finally: + server.shutdown() + assert not server.active + + +def test_occupied_port_does_not_attach_to_existing_server(qtbot): + server = McpServer() + with socket.socket() as occupied: + occupied.bind(("127.0.0.1", 0)) + occupied.listen() + with pytest.raises(OSError): + server.start(sys.executable, ["-c", "pass"], occupied.getsockname()[1]) + assert not server.active + + +def test_early_exit_and_timeout_are_never_ready(qtbot): + server = McpServer() + server.start(sys.executable, ["-c", "exit(3)"], _free_port()) + qtbot.waitUntil(lambda: server.state.startswith("Exited"), timeout=5000) + assert "3" in server.state + server.start(sys.executable, ["-c", "import time; time.sleep(60)"], _free_port()) + qtbot.waitUntil(lambda: server.active) + server.deadline = 0 + server._probe() + qtbot.waitUntil(lambda: not server.active, timeout=5000) + assert not server.state.startswith("Ready") + + +def test_shutdown_terminates_persistent_child_worker(qtbot): + port = _free_port() + child = ( + "import socket,time; s=socket.socket(); " + f"s.bind(('127.0.0.1',{port})); s.listen(); " + "print('CHILD_READY',flush=True); time.sleep(15)" + ) + parent = ( + "import subprocess,sys,time; " + f"subprocess.Popen([sys.executable,'-u','-c',{child!r}]); time.sleep(30)" + ) + server = McpServer() + output = [] + server.output.connect(output.append) + try: + server.process.start(sys.executable, ["-u", "-c", parent]) + qtbot.waitUntil(lambda: "CHILD_READY" in "".join(output), timeout=10000) + server.shutdown() + assert not server.active + + # A child that survived its parent would still own this listening port. + def released(): + try: + with socket.socket() as probe: + probe.bind(("127.0.0.1", port)) + return True + except OSError: + return False + + qtbot.waitUntil(released, timeout=3000) + finally: + server.shutdown() + + +def test_stopped_servers_can_be_destroyed_with_pending_kill_timer(qtbot): + for _ in range(5): + server = McpServer() + server.process.start(sys.executable, ["-c", "import time; time.sleep(60)"]) + qtbot.waitUntil(lambda: server.active) + server.shutdown() + server.deleteLater() + del server + gc.collect() + qtbot.wait(1) + # Run beyond the former singleShot callback's two-second deadline. + qtbot.wait(2100) diff --git a/tests/test_mcp_profiles.py b/tests/test_mcp_profiles.py new file mode 100644 index 00000000..d467bf9a --- /dev/null +++ b/tests/test_mcp_profiles.py @@ -0,0 +1,308 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import json + +import pytest +import tomlkit + +from ansys.tools.installer.mcp_catalog import PRODUCTS +from ansys.tools.installer.mcp_profiles import ( + CLIENTS, + default_profile_path, + render_profile, + save_profile, +) + + +@pytest.mark.parametrize("client", CLIENTS) +@pytest.mark.parametrize("transport", ["stdio", "http"]) +def test_repeated_updates_preserve_named_entry_preferences_and_do_not_duplicate( + client, transport +): + if client == "Claude Desktop" and transport == "http": + pytest.skip("Claude Desktop uses stdio") + product = PRODUCTS[1] + original = ( + "# Keep this comment\nmodel = 'example'\n[mcp_servers.pymechanical]\ncommand = 'old'\nenabled = false\ntool_timeout_sec = 99\n[mcp_servers.pymechanical.env]\nKEEP = 'original'\n[mcp_servers.other]\ncommand = 'unrelated'\n" + if client == "Codex" + else json.dumps( + { + "setting": 42, + "mcp" if client == "OpenCode" else "mcpServers": { + "pymechanical": { + "command": ["old"] if client == "OpenCode" else "old", + "type": "local", + "disabled": True, + "tools": ["allowed_tool"], + "environment" if client == "OpenCode" else "env": { + "KEEP": "original" + }, + }, + "other": {"command": "unrelated"}, + }, + } + ) + ) + first = render_profile( + client, + original, + product, + "new", + ["--transport", "stdio"], + transport=transport, + environment={"ADD": "value"}, + ) + second = render_profile( + client, + first, + product, + "new", + ["--transport", "stdio"], + transport=transport, + environment={"ADD": "value"}, + ) + assert second == first + data = tomlkit.parse(second) if client == "Codex" else json.loads(second) + servers = data[ + ( + "mcp_servers" + if client == "Codex" + else "mcp" if client == "OpenCode" else "mcpServers" + ) + ] + assert set(servers) == {"pymechanical", "other"} + entry = servers["pymechanical"] + assert servers["other"]["command"] == "unrelated" + if client == "Codex": + assert ( + "# Keep this comment" in second + and entry["enabled"] is False + and entry["tool_timeout_sec"] == 99 + ) + else: + assert ( + data["setting"] == 42 + and entry["disabled"] is True + and entry["tools"] == ["allowed_tool"] + ) + if transport == "stdio": + assert entry["environment" if client == "OpenCode" else "env"] == { + "KEEP": "original", + "ADD": "value", + } + else: + assert ( + "env" not in entry and "environment" not in entry and "command" not in entry + ) + + +def test_official_aliases_consolidate_and_custom_launcher_names_are_reused(): + product = PRODUCTS[1] + text = json.dumps( + { + "mcpServers": { + "pymechanical-mcp": {"command": "old", "disabled": True}, + "ansys-mechanical-mcp": {"env": {"KEEP": "yes"}}, + "other": {"command": "keep"}, + } + } + ) + result = json.loads(render_profile("Cursor", text, product, "new", []))[ + "mcpServers" + ] + assert set(result) == {"pymechanical-mcp", "other"} + assert result["pymechanical-mcp"]["disabled"] is True + assert result["pymechanical-mcp"]["env"] == {"KEEP": "yes"} + text = json.dumps( + { + "mcpServers": { + "my_solver_tools": {"command": "uvx", "args": ["ansys-mechanical-mcp"]} + } + } + ) + result = json.loads(render_profile("Cursor", text, product, "new", []))[ + "mcpServers" + ] + assert set(result) == {"my_solver_tools"} + text = json.dumps( + { + "mcpServers": { + "one": {"command": "ansys-mechanical-mcp"}, + "two": {"command": "ansys-mechanical-mcp"}, + } + } + ) + with pytest.raises(ValueError, match="Multiple custom"): + render_profile("Cursor", text, product, "new", []) + + +def test_opencode_new_profiles_use_v2_and_legacy_profiles_keep_v1(): + for transport, expected in ( + ("stdio", {"type": "local", "command": ["server", "--example"]}), + ("http", {"type": "remote", "url": "http://127.0.0.1:8080/mcp"}), + ): + data = json.loads( + render_profile( + "OpenCode", + "", + PRODUCTS[0], + "server", + ["--example"], + transport=transport, + ) + ) + assert data == {"mcp": {"servers": {"pyaedt-mcp": expected}}} + text = '{"mcp":{"pyaedt-mcp":{"type":"local","command":["old"]}}}' + result = json.loads(render_profile("OpenCode", text, PRODUCTS[0], "new", [])) + assert "servers" not in result["mcp"] + assert result["mcp"]["pyaedt-mcp"]["command"] == ["new"] + with pytest.raises(ValueError, match="mixes V1 and V2"): + render_profile( + "OpenCode", + '{"mcp":{"servers":{},"old":{"type":"local","command":["old"]}}}', + PRODUCTS[0], + "new", + [], + ) + + +@pytest.mark.parametrize("client", CLIENTS) +def test_merge_preserves_other_mcp_and_settings(client, tmp_path): + container = "mcp" if client == "OpenCode" else "mcpServers" + original = ( + "# user comment\nmodel = 'example'\n[mcp_servers.other]\ncommand = 'keep'\n" + if client == "Codex" + else json.dumps({"setting": True, container: {"other": {"command": "keep"}}}) + ) + command = tmp_path / "path with spaces/ansys-aedt-mcp" + rendered = render_profile( + client, original, PRODUCTS[0], command, ["--transport", "stdio"] + ) + if client == "Codex": + data = tomlkit.parse(rendered) + assert "# user comment" in rendered + assert data["model"] == "example" + servers = data["mcp_servers"] + else: + data = json.loads(rendered) + assert data["setting"] is True + servers = data[container] + assert servers["other"] == {"command": "keep"} + profile = servers["pyaedt-mcp"] + if client == "OpenCode": + assert profile["command"] == [str(command), "--transport", "stdio"] + else: + assert profile["command"] == str(command) + assert profile["args"] == ["--transport", "stdio"] + + +def test_codex_replacement_removes_old_transport_and_env(): + original = """# retained +[mcp_servers.pyaedt-mcp] +command = 'old' +args = ['--old'] +[mcp_servers.pyaedt-mcp.env] +OLD = 'value' +[mcp_servers.other] +command = 'keep' +""" + rendered = render_profile( + "Codex", original, PRODUCTS[0], "new", [], transport="http", port=9000 + ) + data = tomlkit.parse(rendered) + assert data["mcp_servers"]["pyaedt-mcp"] == { + "url": "http://127.0.0.1:9000/mcp", + "startup_timeout_sec": 60, + } + assert data["mcp_servers"]["other"]["command"] == "keep" + assert "# retained" in rendered + + +def test_vscode_current_and_legacy_formats_and_personal_default(tmp_path): + current = json.loads(render_profile("VS Code", "", PRODUCTS[0], "server", [])) + assert current["mcpServers"]["pyaedt-mcp"]["type"] == "stdio" + legacy = json.loads( + render_profile( + "VS Code", '{"inputs":[]}', PRODUCTS[0], "server", [], vscode_legacy=True + ) + ) + assert legacy["servers"]["pyaedt-mcp"]["type"] == "stdio" + assert legacy["inputs"] == [] + assert ( + default_profile_path("VS Code", home=tmp_path, environ={}) + == tmp_path / ".copilot/mcp-config.json" + ) + assert ( + default_profile_path( + "VS Code", home=tmp_path, environ={"COPILOT_HOME": str(tmp_path / "custom")} + ) + == tmp_path / "custom/mcp-config.json" + ) + + +@pytest.mark.parametrize( + "original", ["[]", '{"mcpServers": []}', '{"x":1,"x":2}', "{ // comment\n }"] +) +def test_invalid_json_not_overwritten(original): + with pytest.raises(ValueError): + render_profile("Cursor", original, PRODUCTS[0], "exe", []) + + +def test_claude_desktop_and_lumerical_transport_limits(): + with pytest.raises(ValueError, match="stdio"): + render_profile("Claude Desktop", "", PRODUCTS[0], "exe", [], transport="http") + with pytest.raises(ValueError, match="stdio"): + render_profile("Cursor", "", PRODUCTS[4], "exe", [], transport="http") + + +def test_backups_and_concurrent_change(tmp_path): + path = tmp_path / "mcp.json" + original = '{"existing": true}' + path.write_text(original) + backup = save_profile(path, original, '{"updated":true}') + assert backup.read_text() == original + assert path.read_text() == '{"updated":true}' + with pytest.raises(ValueError, match="changed since preview"): + save_profile(path, original, "{}") + assert path.read_text() == '{"updated":true}' + + +def test_client_paths_respect_platform_and_environment(tmp_path): + assert ( + default_profile_path( + "Claude Desktop", tmp_path, {"APPDATA": str(tmp_path / "roaming")}, True + ) + == tmp_path / "roaming/Claude/claude_desktop_config.json" + ) + assert ( + default_profile_path( + "OpenCode", tmp_path, {"XDG_CONFIG_HOME": str(tmp_path / "xdg")}, False + ) + == tmp_path / "xdg/opencode/opencode.json" + ) + assert ( + default_profile_path( + "Codex", tmp_path, {"CODEX_HOME": str(tmp_path / "codex")}, False + ) + == tmp_path / "codex/config.toml" + ) diff --git a/tests/test_mcp_releases.py b/tests/test_mcp_releases.py new file mode 100644 index 00000000..a699310d --- /dev/null +++ b/tests/test_mcp_releases.py @@ -0,0 +1,254 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from pathlib import Path +import sys +import zipfile + +import pytest +import requests + +from ansys.tools.installer import mcp_backend as backend +from ansys.tools.installer import mcp_releases as releases +from ansys.tools.installer.mcp_catalog import PRODUCT_BY_KEY, PRODUCTS +from ansys.tools.installer.mcp_releases import PythonInfo, ReleaseInfo + + +class Response: + def __init__(self, data=None, text=""): + self.data = data + self.text = text + + def raise_for_status(self): + pass + + def json(self): + return self.data + + +def test_latest_is_resolved_again_and_pinned_exactly(monkeypatch): + product = PRODUCTS[0] + versions = iter(["1.0.0", "1.0.1"]) + calls = [] + + def get(url, timeout): + calls.append(url) + assert timeout == 20 + return Response( + { + "info": { + "name": product.package, + "version": next(versions), + "requires_python": ">=3.13,<3.15", + }, + "urls": [{"yanked": False}], + } + ) + + monkeypatch.setattr(releases.requests, "get", get) + assert releases.published_release(product).requirement == "ansys-aedt-mcp==1.0.0" + assert releases.published_release(product).requirement == "ansys-aedt-mcp==1.0.1" + assert calls == ["https://pypi.org/pypi/ansys-aedt-mcp/json"] * 2 + + +def test_yanked_or_wrong_package_cannot_be_selected(monkeypatch): + product = PRODUCTS[0] + data = { + "info": {"name": product.package, "version": "1.0"}, + "urls": [{"yanked": True}], + } + monkeypatch.setattr( + releases.requests, "get", lambda *args, **kwargs: Response(data) + ) + with pytest.raises(ValueError, match="non-yanked"): + releases.published_release(product) + data["info"]["name"] = "unrelated-package" + with pytest.raises(ValueError, match="different package"): + releases.published_release(product) + + +@pytest.mark.parametrize( + "key,version,supported", + [ + ("pyaedt", "3.12.9", False), + ("pyaedt", "3.13.1", True), + ("pyaedt", "3.15.0", False), + ("pymechanical", "3.11.9", False), + ("pymechanical", "3.14.0", True), + ("pymechanical", "3.15.0", False), + ("pyfluent", "3.11.9", False), + ("pyfluent", "3.12.0", True), + ("pymapdl", "3.11.9", False), + ("pymapdl", "3.14.0", True), + ("pymapdl", "3.15.0", False), + ("pylumerical", "3.10.9", False), + ("pylumerical", "3.11.9", True), + ("pycfx", "3.11.9", False), + ("pycfx", "3.14.0", True), + ("pycfx", "3.15.0", False), + ], +) +def test_documented_python_ranges(key, version, supported): + product = PRODUCT_BY_KEY[key] + release = ReleaseInfo("1.0", ">=3.10,<4", "pkg==1.0") + info = PythonInfo("python", version, 64) + if supported: + assert releases.validate_python(info, product, release) == info + else: + with pytest.raises(ValueError, match="requires 64-bit Python"): + releases.validate_python(info, product, release) + + +def test_selected_release_constraints_override_broader_product_baseline(): + product = PRODUCT_BY_KEY["pyfluent"] + release = ReleaseInfo("9.0", ">=3.13.4,!=3.13.5,<3.14", "pkg==9.0") + for version in ("3.12.9", "3.13.3", "3.13.5", "3.14.0"): + with pytest.raises(ValueError): + releases.validate_python( + PythonInfo("python", version, 64), product, release + ) + releases.validate_python(PythonInfo("python", "3.13.6", 64), product, release) + with pytest.raises(ValueError): + releases.validate_python(PythonInfo("python", "3.13.6", 32), product, release) + + +def test_automatic_selection_keeps_supported_python_and_skips_incompatible(monkeypatch): + product = PRODUCTS[0] + release = ReleaseInfo("1.0", ">=3.13,<3.14", "pkg==1.0") + versions = {"old": "3.12.9", "too-new": "3.14.0", "supported": "3.13.6"} + monkeypatch.setattr( + releases, "inspect_python", lambda path: PythonInfo(path, versions[path], 64) + ) + assert ( + releases.compatible_python( + product, release, "old", ["too-new", "supported"] + ).executable + == "supported" + ) + assert ( + releases.compatible_python(product, release, "supported", ["old"]).executable + == "supported" + ) + + +def test_source_uses_selected_branch_python_declaration(monkeypatch): + def get(url, params, headers, timeout): + assert ( + url + == "https://api.github.com/repos/ansys/pyaedt-mcp/contents/pyproject.toml" + ) + assert params == {"ref": "feature/new-python"} + assert headers["Accept"] == "application/vnd.github.raw+json" + return Response( + text='[project]\nname="ansys-aedt-mcp"\nrequires-python=">=3.14,<3.15"\n' + ) + + monkeypatch.setattr(releases.requests, "get", get) + assert ( + releases.source_release( + PRODUCTS[0], "feature/new-python", "git-requirement" + ).requires_python + == ">=3.14,<3.15" + ) + + +def test_probe_reports_actual_python(): + info = releases.inspect_python(sys.executable) + assert info.version == ".".join(str(part) for part in sys.version_info[:3]) + assert info.bits == 64 + assert Path(info.executable).is_absolute() + + +def test_newest_local_wheel_is_resolved_without_network(tmp_path, monkeypatch): + product = PRODUCTS[0] + monkeypatch.setattr( + releases.requests, + "get", + lambda *args, **kwargs: pytest.fail("Offline must not access the network"), + ) + for version in ("0.1.0", "0.2.0", "0.3.0rc1"): + name = f"ansys_aedt_mcp-{version}" + with zipfile.ZipFile(tmp_path / f"{name}-py3-none-any.whl", "w") as archive: + archive.writestr( + f"{name}.dist-info/METADATA", + f"Name: {product.package}\nVersion: {version}\nRequires-Python: >=3.13\n", + ) + assert releases.wheelhouse_release(product, tmp_path).version == "0.2.0" + assert releases.wheelhouse_release(product, tmp_path, "0.1.0").version == "0.1.0" + + +def test_incompatible_existing_environment_is_preserved(tmp_path, monkeypatch): + product = PRODUCTS[0] + root = tmp_path / "existing" + python = backend.python_executable(root) + python.parent.mkdir(parents=True) + python.touch() + marker = root / "pyvenv.cfg" + marker.write_text("keep") + monkeypatch.setattr( + backend, + "published_release", + lambda *args: ReleaseInfo("1.0", ">=3.13", "ansys-aedt-mcp==1.0"), + ) + monkeypatch.setattr( + backend, "inspect_python", lambda path: PythonInfo(str(path), "3.12.9", 64) + ) + with pytest.raises(ValueError, match="existing environment was preserved"): + backend.prepare_installation(product, root, sys.executable, custom=True) + assert marker.read_text() == "keep" + + +def test_online_latest_failure_never_becomes_unpinned_install(tmp_path, monkeypatch): + def fail(*args): + raise requests.ConnectionError("offline") + + monkeypatch.setattr(backend, "published_release", fail) + with pytest.raises(requests.ConnectionError): + backend.prepare_installation(PRODUCTS[0], tmp_path / "new", sys.executable) + assert not (tmp_path / "new").exists() + + +def test_online_latest_always_upgrades_even_from_install_button(tmp_path, monkeypatch): + product = PRODUCTS[0] + release = ReleaseInfo("9.0", ">=3.13", "ansys-aedt-mcp==9.0") + interpreter = PythonInfo(sys.executable, "3.13.6", 64) + monkeypatch.setattr(backend, "published_release", lambda *args: release) + monkeypatch.setattr(backend, "compatible_python", lambda *args: interpreter) + plan = backend.prepare_installation(product, tmp_path / "new", sys.executable) + assert "--upgrade" in plan.commands[-2] + assert plan.commands[-2][-1] == "ansys-aedt-mcp==9.0" + + +def test_manager_discovers_python_313_and_314_for_mcp_selection(monkeypatch): + from ansys.tools.installer import find_python + + def output(command, text): + if command[0] == "which" and command[1] in ("python3.13", "python3.14"): + return f"/opt/managed/{command[1]}\n" + if command[0] in ("/opt/managed/python3.13", "/opt/managed/python3.14"): + return "Python " + command[0].rsplit("python", 1)[1] + ".1\n" + raise FileNotFoundError(command[0]) + + monkeypatch.setattr(find_python.subprocess, "check_output", output) + result = find_python._find_installed_python_linux() + assert result["/opt/managed/python3.13"][0] == "3.13.1" + assert result["/opt/managed/python3.14"][0] == "3.14.1" diff --git a/tests/test_mcp_tab.py b/tests/test_mcp_tab.py new file mode 100644 index 00000000..df0d7a61 --- /dev/null +++ b/tests/test_mcp_tab.py @@ -0,0 +1,689 @@ +# Copyright (C) 2023 - 2026 Synopsys, Inc. and ANSYS, Inc. All rights reserved. +# SPDX-License-Identifier: MIT +# +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import json +from pathlib import Path +import subprocess +import sys +import threading +import zipfile + +from PySide6 import QtCore +import pytest + +from ansys.tools.installer import installed_table, mcp_backend +from ansys.tools.installer.mcp_backend import console_executable, installed_version +from ansys.tools.installer.mcp_catalog import PRODUCT_BY_KEY +from ansys.tools.installer.mcp_releases import ReleaseInfo +from ansys.tools.installer.mcp_tab import McpTab, _Task + + +@pytest.fixture(autouse=True) +def discovered_environments(monkeypatch): + """Keep UI discovery deterministic and release checks off the network.""" + monkeypatch.setattr( + installed_table, + "find_all_python", + lambda: { + str(Path(sys.executable).parent): ( + ".".join(map(str, sys.version_info[:3])), + False, + ) + }, + ) + monkeypatch.setattr(installed_table, "find_miniforge", lambda: {}) + monkeypatch.setattr(installed_table, "get_all_python_venv", lambda: {}) + real_versions = mcp_backend.available_versions + monkeypatch.setattr( + "ansys.tools.installer.mcp_tab.available_versions", + lambda product, **options: ( + real_versions(product, **options) + if options.get("wheelhouse") + else ["2.0", "1.0"] + ), + ) + monkeypatch.setattr( + mcp_backend, + "published_release", + lambda product, version="": ReleaseInfo( + version or "1.0", product.python, f"{product.package}=={version or '1.0'}" + ), + ) + + +@pytest.fixture +def tab(qtbot, tmp_path): + widget = McpTab(directory=tmp_path / "manager with spaces") + qtbot.addWidget(widget) + yield widget + widget.shutdown() + qtbot.waitUntil( + lambda: QtCore.QThreadPool.globalInstance().activeThreadCount() == 0, + timeout=10000, + ) + + +def _pick_version(tab, version): + if tab.version.findText(version) < 0: + tab.version.addItem(version) + tab.version.setCurrentText(version) + + +def _select(tab, key): + for index in range(tab.product_select.count()): + if tab.product_select.itemText(index) == PRODUCT_BY_KEY[key].name: + tab.product_select.setCurrentIndex(index) + return + raise AssertionError(key) + + +@pytest.mark.parametrize("fails", [False, True]) +def test_metadata_task_finishes_safely_after_qt_teardown(qapp, fails): + import shiboken6 + + calls = [] + + def finish(): + calls.append(True) + if fails: + raise ValueError("Request finished after application shutdown") + return ["1.0"] + + task = _Task(finish) + shiboken6.delete(task.signals) + task.run() + assert calls == [True] + + +def test_environment_discovery_never_blocks_tab_selection(tab, qtbot, monkeypatch): + release = threading.Event() + started = threading.Event() + calls = [] + gui_thread = threading.get_ident() + + def discover(): + calls.append(threading.get_ident()) + started.set() + release.wait(5) + return {} + + monkeypatch.setattr(installed_table, "find_all_python", discover) + assert not calls # Construction did not repeat host APM discovery. + try: + tab.show() + qtbot.waitUntil(started.is_set) + heartbeat = [] + QtCore.QTimer.singleShot(0, lambda: heartbeat.append(True)) + qtbot.waitUntil(lambda: bool(heartbeat)) + assert tab._discovery_pending + assert calls == [calls[0]] and calls[0] != gui_thread + finally: + release.set() + qtbot.waitUntil(lambda: not tab._discovery_pending) + tab.hide() + tab.show() + assert len(calls) == 1 + + +def test_ansys_python_discovery_is_hidden_and_bounded(monkeypatch): + from ansys.tools.installer import find_python + + calls = [] + monkeypatch.setattr( + find_python, "get_available_ansys_installations", lambda: {271: "ansys"} + ) + monkeypatch.setattr(find_python, "ANSYS_SUPPORTED_PYTHON_VERSIONS", ["3_13"]) + monkeypatch.setattr(find_python.os.path, "exists", lambda path: True) + monkeypatch.setattr( + find_python.subprocess, "CREATE_NO_WINDOW", 0x08000000, raising=False + ) + monkeypatch.setattr( + find_python.subprocess, + "check_output", + lambda *a, **k: calls.append(k) or "Python 3.13.15", + ) + assert find_python._find_installed_ansys_python_win() + assert calls == [{"text": True, "creationflags": 0x08000000, "timeout": 10}] + + +def test_previously_blank_vscode_destination_gets_a_personal_default(qtbot, tmp_path): + (tmp_path / "settings.json").write_text( + json.dumps({"pyaedt": {"client": "VS Code", "profile_path": ""}}), + encoding="utf-8", + ) + widget = McpTab(directory=tmp_path) + qtbot.addWidget(widget) + try: + assert Path(widget.profile_path.text()).name == "mcp-config.json" + assert widget.vscode_format.currentData() is False + finally: + widget.shutdown(save_settings=False) + + +def test_release_dropdown_automatic_cache_and_stale_results(tab, qtbot, monkeypatch): + calls = [] + monkeypatch.setattr( + "ansys.tools.installer.mcp_tab.available_versions", + lambda product: calls.append(product.key) or ["9.2", "9.1"], + ) + tab.show() + qtbot.waitUntil(lambda: tab.version.findText("9.2") >= 0) + tab.version.requested.emit() + assert calls == ["pyaedt"] + _pick_version(tab, "9.1") + tab._versions_fetched(("pymechanical", ["8.0"], None), None) + assert tab.version.currentText() == "9.1" and tab.version.findText("8.0") < 0 + tab.source.setCurrentIndex(2) + before = list(calls) + tab.version.requested.emit() + assert calls == before + tab.source.setCurrentIndex(0) + assert tab.version.currentText() == "Latest" + + +def test_installed_launch_controls_validate_and_invalidate_profile(tab, monkeypatch): + monkeypatch.setattr( + "ansys.tools.installer.mcp_tab.installed_version", lambda *args: "1.0" + ) + signature = tab._launch_signature() + schema = [ + dict( + flags=["--static-tools"], + kind="flag", + nargs=0, + choices=None, + type="str", + help="Use static tools", + default=False, + ), + dict( + flags=["--transport"], + kind="value", + nargs=None, + choices=["stdio", "http"], + type="str", + help="Transport", + default="stdio", + ), + ] + tab._launch_loaded((signature, schema, None), None) + assert tab.launch_choice.count() == 2 # Managed transport cannot be added twice. + tab._add_launch_option(1) + assert "--static-tools" in tab._arguments("stdio") + tab._profile_preview = ("path", "old", "new") + tab._remove_launch_option("--static-tools") + assert tab._profile_preview is None + _select(tab, "pymechanical") + tab._launch_loaded((signature, schema, None), None) + assert tab._launch_context is None + + +def test_product_settings_are_independent_and_persist(tab): + tab.http_port.setValue(9090) + tab.extra.setPlainText('["--version", "2026.1"]') + _select(tab, "pyfluent") + assert tab.http_port.value() != 9090 + assert tab.extra.toPlainText() == "[]" + _select(tab, "pyaedt") + assert tab.http_port.value() == 9090 + assert json.loads(tab.extra.toPlainText()) == ["--version", "2026.1"] + saved = json.loads(tab.settings_path.read_text()) + assert saved["pyaedt"]["http_port"] == 9090 + + +def test_lumerical_only_offers_stdio(tab): + _select(tab, "pylumerical") + assert tab.transport.count() == 1 + assert tab.transport.currentData() == "stdio" + assert not tab.start_button.isEnabled() + assert tab._arguments("stdio") == [] + + +def test_aedt_connection_arguments_and_validation(tab): + tab.connect.setChecked(True) + tab.solver_port.setValue(50055) + tab.graphical.setChecked(True) + arguments = tab._arguments("http") + assert "--connect" in arguments + assert "--graphical" in arguments + assert arguments[arguments.index("--port") + 1] == "50055" + tab.extra.setPlainText('{"invalid":true}') + with pytest.raises(ValueError, match="JSON array"): + tab._arguments("stdio") + tab.environment_json.setPlainText('{"BAD=NAME":"value"}') + with pytest.raises(ValueError, match="Environment variables"): + tab._environment_variables() + + +def test_corrupt_settings_are_not_silently_overwritten(qtbot, tmp_path): + path = tmp_path / "settings.json" + path.write_text("{corrupt") + widget = McpTab(directory=tmp_path) + qtbot.addWidget(widget) + try: + with pytest.raises(ValueError, match="Repair"): + widget._save() + assert path.read_text() == "{corrupt" + finally: + widget.shutdown() + + +def _wheel(directory, version="0.0.0", requires_python=">=3.12"): + """Create a solver-free console package for an actual offline pip install.""" + name = f"ansys_mechanical_mcp-{version}" + files = { + "apm_mcp_fixture.py": "def main():\n print('fixture MCP')\n", + f"{name}.dist-info/METADATA": f"Metadata-Version: 2.1\nName: ansys-mechanical-mcp\nVersion: {version}\nRequires-Python: {requires_python}\n", + f"{name}.dist-info/WHEEL": "Wheel-Version: 1.0\nGenerator: apm-test\nRoot-Is-Purelib: true\nTag: py3-none-any\n", + f"{name}.dist-info/entry_points.txt": "[console_scripts]\nansys-mechanical-mcp = apm_mcp_fixture:main\n", + } + files[f"{name}.dist-info/RECORD"] = "".join(f"{path},,\n" for path in files) + directory.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(directory / f"{name}-py3-none-any.whl", "w") as archive: + for path, content in files.items(): + archive.writestr(path, content) + + +@pytest.mark.skipif( + sys.version_info < (3, 12), + reason="MCPs require a separate Python 3.12+ interpreter", +) +def test_offline_install_through_ui_and_profile_preview(tab, qtbot, tmp_path): + _select(tab, "pymechanical") + wheels = tmp_path / "wheel house" + _wheel(wheels) + tab.select_python(sys.executable) + tab.source.setCurrentIndex(2) + tab.wheelhouse_path.setText(str(wheels)) + _pick_version(tab, "0.0.0") + tab._install(False) + qtbot.waitUntil(lambda: not tab._preparing and not tab.queue.active, timeout=90000) + assert console_executable( + tab.environment, tab.product + ).is_file(), tab.log.toPlainText() + assert installed_version(tab.environment, tab.product) == "0.0.0" + assert "completed" in tab.status.text(), tab.log.toPlainText() + tab.client.setCurrentText("Cursor") + configuration = tmp_path / "client/mcp.json" + configuration.parent.mkdir() + configuration.write_text('{"mcpServers":{"existing":{"command":"keep"}}}') + tab.profile_path.setText(str(configuration)) + tab.environment_json.setPlainText('{"EXAMPLE":"value"}') + tab._review_or_write_profile() + assert "pymechanical-mcp" not in configuration.read_text() + assert tab.write_profile_button.isEnabled() + assert tab.write_profile_button.text() == "Save reviewed configuration" + tab._review_or_write_profile() + data = json.loads(configuration.read_text())["mcpServers"] + assert data["existing"]["command"] == "keep" + assert data["pymechanical-mcp"]["env"] == {"EXAMPLE": "value"} + assert list(configuration.parent.glob("*.bak")) + tab._preview_profile() + tab.extra.setPlainText('["--static-tools"]') + assert tab._profile_preview is None + assert tab.write_profile_button.text() == "Review configuration…" + assert "Review the changes" not in tab.status.text() + + +def test_invalid_install_source_shows_error_without_starting(tab): + tab.source.setCurrentIndex(1) + tab.branch.setText("main#bad") + tab._try(lambda: tab._install(False)) + assert "Git branch" in tab.status.text() + assert not tab.queue.active + + +def test_uses_the_same_apm_selector_widgets(tab): + assert isinstance(tab.python_select, installed_table.DataComboBox) + assert tab.python_select.installed_python and tab.python_select.installed_forge + assert isinstance(tab.environment_select, installed_table.DataComboBox) + assert tab.environment_select.created_venv + + +def test_source_options_and_advanced_controls_are_progressive(tab): + assert not tab.install_advanced_toggle.isChecked() + assert not tab.server_advanced_toggle.isChecked() + assert tab.preview_section.isHidden() + assert tab.branch.isHidden() and tab.wheelhouse_row.isHidden() + tab.source.setCurrentIndex(1) + assert not tab.branch.isHidden() + assert tab.version_row.isHidden() and tab.wheelhouse_row.isHidden() + tab.source.setCurrentIndex(2) + assert tab.branch.isHidden() + assert not tab.wheelhouse_row.isHidden() and not tab.version_row.isHidden() + assert not hasattr(tab, "versions_button") + + +def test_missing_saved_python_path_does_not_grow_on_refresh(tab, tmp_path): + missing = str(tmp_path / "removed" / "python.exe") + tab.select_python(missing) + tab._select_path(tab.python_select, missing) + assert tab._base_python() == missing + tab._refresh_choices() + tab._select_path(tab.python_select, missing) + assert tab._base_python() == missing + + +def test_discovered_directory_named_python_is_not_treated_as_an_executable( + tab, tmp_path +): + directory = tmp_path / "python" + executable = mcp_backend.python_executable(directory) + executable.parent.mkdir(parents=True) + executable.touch() + assert tab._python_choice(directory) == str(executable) + + +def test_exact_release_updates_python_choices_dynamically( + tab, qtbot, tmp_path, monkeypatch +): + from ansys.tools.installer import mcp_compatibility + from ansys.tools.installer.mcp_releases import PythonInfo + + versions = ("3.13.4", "3.13.8", "3.14.2") + paths = [ + tmp_path / version / ("python.exe" if sys.platform == "win32" else "python") + for version in versions + ] + for path in paths: + path.parent.mkdir() + path.touch() + inventory = {str(path): (version, False) for path, version in zip(paths, versions)} + monkeypatch.setattr(installed_table, "find_all_python", lambda: inventory) + monkeypatch.setattr( + mcp_compatibility, + "inspect_python", + lambda path: PythonInfo( + path, versions[[str(p) for p in paths].index(path)], 64 + ), + ) + monkeypatch.setattr( + mcp_backend, + "published_release", + lambda product, version="": ReleaseInfo( + version or "1.0", + ">=3.14,<3.15" if version == "2.0" else ">=3.13.5,<3.14", + product.package, + ), + ) + tab._manual_pythons.clear() + tab._refresh_choices() + tab.show() + qtbot.waitUntil(lambda: tab._compatibility is not None, timeout=10000) + assert tab._base_python() == str(paths[1]) + assert not tab.python_select.model().item(0).isEnabled() + assert tab.python_select.model().item(1).isEnabled() + assert not tab.python_select.model().item(2).isEnabled() + assert tab.python_select.view().isRowHidden(0) + assert not tab.python_select.view().isRowHidden(1) + assert tab.python_select.view().isRowHidden(2) + _pick_version(tab, "2.0") + qtbot.waitUntil( + lambda: tab._compatibility is not None + and tab._compatibility.release.version == "2.0", + timeout=10000, + ) + assert tab._base_python() == str(paths[2]) + assert tab.python_select.model().item(2).isEnabled() + assert not tab.python_select.model().item(1).isEnabled() + assert not tab.python_select.view().isRowHidden(2) + assert tab.python_select.view().isRowHidden(1) + + +def test_late_compatibility_response_cannot_replace_current_selection(tab): + from ansys.tools.installer.mcp_compatibility import Compatibility + + revision = tab._compatibility_revision + stale = Compatibility(ReleaseInfo("old", ">=3.13", "old"), {}, {}, {}) + _pick_version(tab, "2.0") + tab._compatibility_checked((revision, stale, ""), None) + assert tab._compatibility is None + assert tab.version.currentText() == "2.0" + + +def test_incompatible_existing_environment_is_not_silently_retargeted( + tab, qtbot, tmp_path, monkeypatch +): + from ansys.tools.installer import mcp_compatibility + from ansys.tools.installer.mcp_releases import PythonInfo + + root = tmp_path / "selected-existing" + executable = mcp_backend.python_executable(root) + executable.parent.mkdir(parents=True) + executable.touch() + marker = root / "pyvenv.cfg" + marker.write_text("preserved") + real_probe = mcp_compatibility.inspect_python + monkeypatch.setattr( + mcp_compatibility, + "inspect_python", + lambda path: ( + PythonInfo(path, "3.12.9", 64) + if path == str(executable) + else real_probe(path) + ), + ) + tab.select_environment(root) + tab.show() + qtbot.waitUntil(lambda: tab._compatibility is not None, timeout=10000) + assert tab.environment == root + assert not tab.install_button.isEnabled() + assert "Select a supported" in tab.python_hint.text() + assert marker.read_text() == "preserved" + + +def test_coding_agent_connection_defaults_and_workspace_choice( + tab, monkeypatch, tmp_path +): + tab.client.setCurrentText("VS Code") + assert Path(tab.profile_path.text()).name == "mcp-config.json" + monkeypatch.setattr( + "PySide6.QtWidgets.QFileDialog.getExistingDirectory", + lambda *args: str(tmp_path), + ) + tab.vscode_format.setCurrentIndex(1) + tab._browse_workspace() + assert Path(tab.profile_path.text()) == tmp_path / ".vscode/mcp.json" + tab.transport.setCurrentIndex(1) + assert tab._transport() == "http" + tab.client.setCurrentText("Claude Desktop") + assert tab.transport.count() == 1 and tab._transport() == "stdio" + + +def test_existing_dedicated_environment_displays_its_actual_python( + tab, qtbot, monkeypatch +): + from ansys.tools.installer import mcp_compatibility + from ansys.tools.installer.mcp_releases import PythonInfo + + executable = mcp_backend.python_executable(tab.environment) + executable.parent.mkdir(parents=True) + executable.touch() + real_probe = mcp_compatibility.inspect_python + monkeypatch.setattr( + mcp_compatibility, + "inspect_python", + lambda path: ( + PythonInfo(path, "3.13.9", 64) + if path == str(executable) + else real_probe(path) + ), + ) + tab.show() + qtbot.waitUntil(lambda: tab._compatibility is not None, timeout=10000) + assert "3.13.9" in tab.managed_python_info.text() + assert not tab.python_select.isHidden() + assert tab.python_caption.text() == "Select Python version" + + +def test_actions_stay_visible_with_logs_and_previews(tab, qtbot): + tab.resize(660, 560) + tab.show() + tab.log_group.setChecked(True) + for index, buttons in ( + (0, (tab.install_button, tab.save_button)), + (1, (tab.start_button, tab.server_save_button)), + (2, (tab.write_profile_button,)), + ): + tab.pages.setCurrentIndex(index) + if index == 2: + tab.preview_section.show() + qtbot.wait(20) + assert tab.action_stack.currentIndex() == index + for button in buttons: + assert button.isVisible() + point = button.mapTo(tab, QtCore.QPoint(0, 0)) + assert tab.rect().contains(QtCore.QRect(point, button.size())) + + +def test_shutdown_reaps_running_server(tab, qtbot): + server = tab.servers[tab.product.key] + server.process.start(sys.executable, ["-c", "import time; time.sleep(60)"]) + qtbot.waitUntil(lambda: server.active) + tab.shutdown() + assert not server.active + + +@pytest.mark.skipif(sys.version_info < (3, 12), reason="MCP interpreter baseline") +def test_existing_environment_without_pip_is_bootstrapped(tab, qtbot, tmp_path): + _select(tab, "pymechanical") + existing = tmp_path / "existing environment" + subprocess.run( + [sys.executable, "-m", "venv", "--without-pip", str(existing)], check=True + ) + wheels = tmp_path / "wheels" + _wheel(wheels) + tab.select_environment(existing) + tab.source.setCurrentIndex(2) + tab.wheelhouse_path.setText(str(wheels)) + _pick_version(tab, "0.0.0") + tab._install(False) + qtbot.waitUntil(lambda: not tab._preparing and not tab.queue.active, timeout=90000) + assert "completed" in tab.status.text(), tab.log.toPlainText() + assert installed_version(existing, tab.product) == "0.0.0" + + +def test_shared_custom_environment_is_protected_across_products(tab, qtbot, tmp_path): + root = tmp_path / "shared" + root.mkdir() + server = tab.servers["pyaedt"] + server.environment_root = root + server.process.start(sys.executable, ["-c", "import time; time.sleep(60)"]) + qtbot.waitUntil(lambda: server.active) + try: + _select(tab, "pymechanical") + tab.select_environment(root) + assert tab.environment_in_use(root) + assert not tab.install_button.isEnabled() + with pytest.raises(ValueError, match="Stop the server"): + tab._install(False) + finally: + server.shutdown() + + +def test_each_product_renders_in_constrained_window(tab, qtbot, tmp_path): + tab.resize(660, 620) + tab.show() + for index in range(tab.product_select.count()): + tab.product_select.setCurrentIndex(index) + for page in range(tab.pages.count()): + tab.pages.setCurrentIndex(page) + qtbot.wait(10) + assert not tab.grab().isNull() + assert tab.grab().save(str(tmp_path / "mcp-tab.png")) + + +def test_uninstall_can_exit_without_recreating_removed_settings(tab): + assert not tab.settings_path.exists() + tab.shutdown(save_settings=False) + assert not tab.settings_path.exists() + + +def test_latest_is_default_for_every_product(tab): + for index in range(tab.product_select.count()): + tab.product_select.setCurrentIndex(index) + assert tab.version.currentText() == "Latest" + assert tab._version() == "" + + +def test_release_version_is_strict_dropdown_and_offline_versions_load_automatically( + tab, qtbot, tmp_path, monkeypatch +): + _select(tab, "pymechanical") + assert not tab.version.isEditable() and tab.version.lineEdit() is None + wheels = tmp_path / "wheels" + _wheel(wheels, "0.0.0") + _wheel(wheels, "0.0.1") + monkeypatch.setattr( + mcp_backend.requests, + "get", + lambda *a, **k: pytest.fail("Offline version lists must not use the network"), + ) + tab.source.setCurrentIndex(2) + tab.wheelhouse_path.setText(str(wheels)) + tab.version.requested.emit() + qtbot.waitUntil(lambda: tab.version.findText("0.0.1") >= 0) + assert [tab.version.itemText(i) for i in range(tab.version.count())] == [ + "Latest", + "0.0.1", + "0.0.0", + ] + tab.version.setCurrentText("unpublished") + assert tab.version.currentText() == "Latest" + + +@pytest.mark.skipif(sys.version_info < (3, 12), reason="MCP interpreter baseline") +def test_latest_offline_install_upgrades_existing_package(tab, qtbot, tmp_path): + _select(tab, "pymechanical") + wheels = tmp_path / "wheels" + _wheel(wheels, "0.0.0") + tab.source.setCurrentIndex(2) + tab.wheelhouse_path.setText(str(wheels)) + tab.select_python(sys.executable) + tab._install(False) + qtbot.waitUntil(lambda: not tab._preparing and not tab.queue.active, timeout=90000) + assert ( + installed_version(tab.environment, tab.product) == "0.0.0" + ), tab.log.toPlainText() + _wheel(wheels, "0.0.1") + tab._install(False) + qtbot.waitUntil(lambda: not tab._preparing and not tab.queue.active, timeout=90000) + assert ( + installed_version(tab.environment, tab.product) == "0.0.1" + ), tab.log.toPlainText() + assert "--upgrade" in tab.log.toPlainText() + + +@pytest.mark.skipif(sys.version_info < (3, 12), reason="MCP interpreter baseline") +def test_dynamic_selector_checks_release_without_creating_environment( + tab, qtbot, tmp_path +): + _select(tab, "pymechanical") + wheels = tmp_path / "wheels" + _wheel(wheels) + tab.source.setCurrentIndex(2) + tab.wheelhouse_path.setText(str(wheels)) + tab.show() + qtbot.waitUntil(lambda: tab._compatibility is not None, timeout=10000) + assert "Selected Python" in tab.python_hint.text(), tab.status.text() + assert not tab.environment.exists() + assert not tab.queue.active