The tools.py module#

Summary#

check_mechanical_status

Check Mechanical status and non-sensitive MCP session diagnostics.

check_mechanical_installed

Check if Mechanical is installed on the system.

run_python_script

Execute a Python script inside Mechanical.

launch_mechanical

Launch a new Mechanical instance.

connect_to_mechanical

Connect to an existing Mechanical instance.

disconnect_from_mechanical

Disconnect from the connected Mechanical instance.

list_mechanical_instances

List all Mechanical instances running on the local machine.

list_files

List files in the Mechanical working directory.

upload_file

Upload a file to the Mechanical instance.

download_file

Download a file from the Mechanical instance.

download_project

Download the connected Mechanical project’s files as one operation.

clear_mechanical

Clear the Mechanical database.

mechanical_working_directory

Return the working directory of the connected Mechanical instance.

get_model_info

Get information about the current model in Mechanical.

screenshot

Capture a screenshot of the current Mechanical view.

run_python_code

Execute Python code in the persistent Python session for data processing.

create_custom_plot

Create a custom plot using Matplotlib in the persistent Python session.

save_project

Save the current Mechanical project.

open_project

Open an existing Mechanical project file.

solve_analysis

Solve the specified analysis in Mechanical.

export_results

Export results from the solved analysis.

get_results_summary

Return solved result values as structured data.

find_objects

Find objects in the Mechanical Outline tree and return their stable IDs.

describe_api

Describe an object, or search the Mechanical API, of the connected release.

preview_property_change

Validate a property change and show its effect without applying it.

apply_property_change

Apply a property change that was previewed with preview_property_change.

check_script

Check a Mechanical script without running it.

get_mechanical_logs

Return recent log entries from the connected Mechanical instance.

Description#

List of tools in PyMechanical-MCP.

Module detail#

tools.check_mechanical_status(ctx: fastmcp.server.Context) → str#

Check Mechanical status and non-sensitive MCP session diagnostics.

This tool retrieves comprehensive information from the connected Mechanical instance including version, project directory, and connection status. Ownership, transport, pending operations, and persistent Python diagnostics are included even when Mechanical is disconnected. Replaces the former get_session_diagnostics tool.

Parameters:
ctxContext

MCP context containing the server session and application context.

Returns:
str

JSON string containing comprehensive Mechanical status information including:

  • connection: Basic connection information (version, project_directory, is_alive)

  • product_info: Product version and build information

Returns an error message if Mechanical is not available or has exited.

tools.check_mechanical_installed(ctx: fastmcp.server.Context) → str#

Check if Mechanical is installed on the system.

This tool checks whether Ansys Mechanical is properly installed and available on the system by inspecting standard installation paths.

Note

When PyMechanical-MCP runs inside a Docker container, the host filesystem is not accessible. In this case, the tool probes the configured gRPC endpoint instead and reports whether a Mechanical server is reachable.

Returns:
str

Status message indicating whether Mechanical is installed or reachable.

tools.run_python_script(ctx: fastmcp.server.Context, script: str | None = None, file_path: str | None = None) → str#

Execute a Python script inside Mechanical.

This tool runs a Python script block inside the connected Mechanical instance using Mechanical’s scripting API. The script has access to Mechanical’s ExtAPI, DataModel, Model, Tree, and Graphics entry points.

Provide either an inline script string or a file_path pointing to a local Python file. When file_path is given, its contents are read and executed inside Mechanical.

Parameters:
ctxContext

MCP context containing the server session and application context.

scriptstr, optional

The Python script to execute inside Mechanical. Required when file_path is not provided.

file_pathstr, optional

Path to a local Python script file whose contents are executed inside Mechanical. Takes precedence over script when both are provided.

Returns:
str

Script execution result. Returns the string value of the last executed statement, or an empty string if the value cannot be returned as a string.

async tools.launch_mechanical(ctx: fastmcp.server.Context, exec_file: str | None = None, port: int | None = None, batch: bool | None = None, version: str | None = None, transport_mode: str | None = None) → str#

Launch a new Mechanical instance.

This tool starts a new Mechanical instance using PyMechanical’s launch_mechanical function. The launched instance will be automatically connected and stored in the context for subsequent operations. Once connected, additional tools become available to interact with it (including run_python_script, screenshot, and save_project).

It always starts a new process; use connect_to_mechanical to attach to a running instance. Launching is refused when the server’s environment sets PYMECHANICAL_START_INSTANCE=false. If the request is cancelled, the launch continues and is recorded when it finishes; a launch that does not finish within the start timeout plus a grace period is stopped.

Parameters:
ctxContext

MCP context containing the server session and application context.

exec_filestr, default: None

path to the Mechanical executable. If None, the executable matching version is used, or PyMechanical’s default installation when version is also None.

portint, default: None

gRPC port for Mechanical to listen on. If None, 10000 is used.

batchbool | None, default: None

Whether to launch Mechanical in batch mode. When omitted, PyMechanical-MCP tries to ask the client to choose between GUI and batch mode and falls back to GUI mode if elicitation is unavailable.

versionstr, default: None

Mechanical release to run, such as "261", "26.1", or "2026 R1". The launch fails with the list of installed releases when the requested release is not installed. If None, PyMechanical’s default installation (the saved path or the newest installed release) is used.

transport_modestr, default: None

gRPC transport mode for the launched instance. Options are auto, insecure, mtls, and wnua. When None or auto, PyMechanical applies the platform default.

Returns:
str

Launch status message with Mechanical version and connection information.

async tools.connect_to_mechanical(ctx: fastmcp.server.Context, port: int = 10000, ip: str = '127.0.0.1', transport_mode: str | None = None) → str#

Connect to an existing Mechanical instance.

This tool establishes a connection to a running Mechanical instance using the provided port and IP address. The connection is stored for subsequent operations and can be closed using the disconnect_from_mechanical tool. Once connected, additional tools become available to interact with it (including run_python_script, screenshot, and save_project).

Parameters:
ctxContext

MCP context containing the server session and application context.

portint, default: 10000

gRPC port where Mechanical is listening.

ipstr, default: “127.0.0.1”

IP address where Mechanical is running.

transport_modestr, default: None

gRPC transport mode. Options are "auto", "insecure", "mtls", and "wnua". When None or "auto", the mode is determined automatically. On Windows, it defers to PyMechanical’s default ( "wnua"). On Linux/Docker, it uses "mtls" if certificates are found. Otherwise it uses "insecure".

Returns:
str

Connection status message with Mechanical version information.

async tools.disconnect_from_mechanical(ctx: fastmcp.server.Context) → str#

Disconnect from the connected Mechanical instance.

An instance started by launch_mechanical is shut down. An instance attached with connect_to_mechanical (or --connect-on-startup) is only released and keeps running, so a user’s own Mechanical session and its unsaved work are kept. A launch or connection that is still in progress is cancelled; a launch’s own Mechanical process is stopped.

Parameters:
ctxContext

MCP context containing the server session and application context.

Returns:
str

Disconnection status message.

tools.list_mechanical_instances() → str#

List all Mechanical instances running on the local machine.

This tool discovers Mechanical instances running on the machine by scanning for active gRPC servers and their associated metadata.

Note

When the MCP server runs inside a Docker container, host process scanning is not available. In this case, the tool probes the configured gRPC endpoint and reports its reachability.

Returns:
str

Formatted table of Mechanical instances, or reachability status when running in Docker.

tools.list_files(ctx: fastmcp.server.Context) → str#

List files in the Mechanical working directory.

This tool lists all files in the working directory of the connected Mechanical instance.

Parameters:
ctxContext

MCP context containing the server session and application context.

Returns:
str

List of files in the working directory.

tools.upload_file(ctx: fastmcp.server.Context, file_path: str) → str#

Upload a file to the Mechanical instance.

This tool uploads a local file to the Mechanical instance’s working directory.

Parameters:
ctxContext

MCP context containing the server session and application context.

file_pathstr

Path to the local file to upload.

Returns:
str

Upload status message.

tools.download_file(ctx: fastmcp.server.Context, file_name: str, target_dir: str | None = None) → str#

Download a file from the Mechanical instance.

This tool downloads a file from the Mechanical instance’s working directory to the local filesystem.

Parameters:
ctxContext

MCP context containing the server session and application context.

file_namestr

Name of the file to download from the Mechanical working directory. A bare file name (for example "beam.step") is matched by its base name. Glob patterns (for example "*.png") and full paths returned by list_files are also accepted.

target_dirstr, optional

Local directory to save the downloaded file. If None, the current directory is used.

Returns:
str

Download status message with local file path.

tools.download_project(ctx: fastmcp.server.Context, extensions: list[str] | None = None, target_dir: str | None = None) → str#

Download the connected Mechanical project’s files as one operation.

Parameters:
ctxContext

MCP context containing the connected Mechanical instance.

extensionslist[str] | None, optional

Optional file extensions to include, such as ["mechdb", "png"]. When omitted, downloads all project files supported by PyMechanical.

target_dirstr | None, optional

Local directory to receive the downloaded files. Uses the current directory when omitted.

Returns:
str

JSON result containing the downloaded local paths or a structured error.

tools.clear_mechanical(ctx: fastmcp.server.Context) → str#

Clear the Mechanical database.

This tool clears the current database in the Mechanical instance, providing a fresh start for a new analysis. All unsaved model data is lost. The Mechanical process and the connection stay open; use disconnect_from_mechanical to end the session.

Parameters:
ctxContext

MCP context containing the server session and application context.

Returns:
str

Clear status message.

tools.mechanical_working_directory() → str#

Return the working directory of the connected Mechanical instance.

This resource provides the absolute path to the active project directory used by the connected Mechanical instance. The value is resolved lazily each time the resource is read.

Returns:
str

Absolute path to the Mechanical project directory, or a message indicating that Mechanical is not connected.

tools.get_model_info(ctx: fastmcp.server.Context, max_items: int | None = 50) → str#

Get information about the current model in Mechanical.

This tool retrieves information about the current model including geometry, mesh, and analysis settings by executing a script inside Mechanical.

Parameters:
ctxContext

MCP context containing the server session and application context.

max_itemsint or None, default: 50

Maximum entries per name or analysis list (0 to 1000). Zero returns counts only; None explicitly returns every entry. For large models, prefer filtered, paged find_objects calls over an unlimited response.

Returns:
str

JSON string containing model information. Includes project, model, geometry, mesh (counts plus the active mesh metric), analyses_count, named_selections, materials, unit_system, analyses, and boundary_conditions. collection_info reports total and returned counts and truncation per list. Geometry includes body counts by GeometryType and suppression counts, not body names.

tools.screenshot(ctx: fastmcp.server.Context, view_type: str = 'model') → list[mcp.types.TextContent | mcp.types.ImageContent]#

Capture a screenshot of the current Mechanical view.

This tool captures the current graphics view from Mechanical as an image. It can capture model views, mesh views, or result contour plots.

Parameters:
ctxContext

MCP context containing the server session and application context.

view_typestr, default: "model"

View to activate before capturing. Options are "model" (geometry), "mesh", and "result" (the first evaluated result object). If the requested view cannot be activated, the current view is captured instead.

Returns:
list[TextContent | ImageContent]

A list containing:

  • TextContent with the screenshot file path

  • ImageContent with the base64-encoded image data

async tools.run_python_code(ctx: fastmcp.server.Context, code: str, timeout: int = 60) → str#

Execute Python code in the persistent Python session for data processing.

IMPORTANT: This tool runs in a separate Python process and does NOT have access to the Mechanical gRPC connection. Use this tool for:

  • Custom data processing and analysis (NumPy, Pandas, and SciPy)

  • Creating Matplotlib plots and visualizations

  • Postprocessing results exported from Mechanical

  • General Python computations

For code that needs to run inside Mechanical (such as IronPython with ExtAPI or Model), use the ‘run_python_script’ tool instead.

Parameters:
ctxContext

MCP context containing the server session and application context.

codestr

Python code to execute. You should use standard Python libraries. This tool does NOT have access to Mechanical’s ExtAPI, Model, or other internal objects.

timeoutint, default: 60

Maximum time in seconds to allow for code execution.

Returns:
str

Execution result or error message. Returns JSON for structured output.

tools.create_custom_plot(ctx: fastmcp.server.Context, plot_code: str, plot_type: str = 'matplotlib', timeout: int = 60) → list[mcp.types.TextContent | mcp.types.ImageContent] | str#

Create a custom plot using Matplotlib in the persistent Python session.

IMPORTANT: This tool runs in a separate Python process and does not have access to the Mechanical gRPC connection. Use this to:

  • Visualize data that was exported/saved from Mechanical.

  • Create plots from result files (such as CSV and TXT).

  • Perform postprocessing visualizations.

For plots that need data directly from Mechanical, first use run_python_script to export the data to a file. Then use this tool to create the visualization.

Parameters:
ctxContext

MCP context containing the server session and application context.

plot_codestr

Python code to create the plot. You should use matplotlib.pyplot. For Matplotlib, the code should create the figure or plot but not call plt.show(). Use the save_matplotlib_plot() helper function to return the plot.

plot_typestr, default:"matplotlib"

Type of plot. Options are "matplotlib" and "pyvista".

timeoutint, default: 60

Maximum time in seconds for plot generation.

Returns:
list[TextContent | ImageContent]

A list containing:

  • TextContent with the plot creation status message

  • ImageContent with the base64-encoded image data if successful

Or, a JSON string with error details if failed.

tools.save_project(ctx: fastmcp.server.Context, file_path: str | None = None) → str#

Save the current Mechanical project.

This tool saves the current project to disk. If file_path is provided, the project is saved to that location (Save As), overwriting an existing file at that path. Otherwise, the project is saved in place.

Parameters:
ctxContext

MCP context containing the server session and application context.

file_pathstr, default: None

Full path for saving the project (Save As). The path should end with a .mechdb extension. The path is resolved on the connected Mechanical instance, which may be a different machine than the MCP server. If None, the project is saved in the current location.

Returns:
str

Save status message with the project file path.

tools.open_project(ctx: fastmcp.server.Context, file_path: str) → str#

Open an existing Mechanical project file.

This tool opens a MECHDB project file in the connected Mechanical instance. Any unsaved work in the current project is lost.

Parameters:
ctxContext

MCP context containing the server session and application context.

file_pathstr

Full path to the MECHDB file. The path is resolved on the connected Mechanical instance, which may be a different machine than the MCP server, so it is not required to exist on the local filesystem.

Returns:
str

Open status message with project information.

tools.solve_analysis(ctx: fastmcp.server.Context, analysis_index: int = 0, wait: bool = True) → str#

Solve the specified analysis in Mechanical.

This tool runs the solver for the specified analysis and returns the solution status. It checks for common issues and provides diagnostic information if the solve fails.

Parameters:
ctxContext

MCP context containing the server session and application context.

analysis_indexint, default: 0

Index of the analysis to solve (0-based). The default, 0, corresponds to the first analysis.

waitbool, default: True

Whether to block until the solve finishes. When False, the solve is started and the tool returns immediately. The reported status then reflects the solver state at that moment rather than the final outcome.

Returns:
str

JSON string with solution status, timing, and result summary.

tools.export_results(ctx: fastmcp.server.Context, analysis_index: int = 0, result_type: str = 'all', export_format: str = 'png', output_dir: str | None = None) → str#

Export results from the solved analysis.

This tool exports result images (contour plots) and/or data from the current solution. It can export individual result types or all available results at once.

Parameters:
ctxContext

MCP context containing the server session and application context.

analysis_indexint, default: 0

Index of the analysis to export results from (0-based). Use the same index that was passed to solve_analysis.

result_typestr, default: "all"
Type of result to export. Options are "all", "deformation", "stress",

"strain", or a specific result object name.

export_formatstr, default: "png"

Export format. Use "png" for images, "txt" for text data, or "both" for images and text.

output_dirstr, default: None

Directory on the Mechanical host to save exported files. It is created if it does not exist. If None, uses the project directory. Use download_file or download_project to copy the files locally.

Returns:
str

JSON string with export status and file paths.

tools.get_results_summary(ctx: fastmcp.server.Context, analysis_index: int | None = None) → str#

Return solved result values as structured data.

Use this after solve_analysis to read result extrema directly, instead of exporting files and reading them back. Every evaluated result object is reported generically, so custom and user-defined results are included without needing a dedicated tool per result type.

Parameters:
ctxContext

MCP context containing the server session and application context.

analysis_indexint, optional

Restrict the summary to a single analysis (0-based). When None, every analysis in the model is reported.

Returns:
str

JSON string with one entry per analysis, each listing its result objects with their state and their minimum, maximum, and average values and units. Values are null unless the result is solved, so stale values of an obsolete or failed result are never reported.

tools.find_objects(ctx: fastmcp.server.Context, name_contains: str | None = None, category: str | None = None, parent_id: int | None = None, max_depth: int | None = None, limit: int = 100, offset: int = 0) → str#

Find objects in the Mechanical Outline tree and return their stable IDs.

Use the returned object_id values with describe_api and preview_property_change. IDs stay the same for the life of the object, unlike names, which can repeat, and positions, which change when objects are added. Nothing in the model is changed.

Parameters:
ctxContext

MCP context containing the server session and application context.

name_containsstr, optional

Case-insensitive text that the object name must contain.

categorystr, optional

DataModelObjectCategory name, such as Force, FixedSupport, Body, or EquivalentStress. Case-insensitive.

parent_idint, optional

Search below this object only. By default the whole project is searched.

max_depthint, optional

Number of levels below the start object to search. By default all levels are searched.

limitint, default: 100

Maximum number of objects to return, from 1 to 1000. match_count always reports the full number of matches.

offsetint, default: 0

Number of filtered matches to skip in Outline order. Follow next_offset until null to retrieve all matches, including lists larger than 1000. Keep filters unchanged; restart if result_fingerprint changes.

Returns:
str

JSON with objects (object_id, name, category, state, path, depth, and child_count), match_count, truncated, category_counts for every object searched, and the connected product_version and python_engine.

tools.describe_api(ctx: fastmcp.server.Context, object_id: int | None = None, query: str | None = None, details_only: bool = True, name_contains: str | None = None, include_methods: bool = False, limit: int = 30) → str#

Describe an object, or search the Mechanical API, of the connected release.

Pass exactly one of object_id or query. Everything is read from the connected session, so it matches the installed release, including releases newer than the bundled API reference. Nothing in the model is changed.

  • object_id: properties of one object, with current values, units, and allowed enum members. Use this before preview_property_change.

  • query: search API types, properties, methods, and enum members by keywords, such as "element size", "AddFixedSupport", or "contact formulation". A query that names a type, such as "FixedSupport", also returns all members of that type. Use this before writing a script instead of guessing API names.

    Query results include concise installed-documentation summaries where available. An exact Type.Member query also returns parameters, remarks and examples from the connected installation’s XML, with source and truncation metadata. Documentation can be missing or boilerplate; reflection still works offline.

Parameters:
ctxContext

MCP context containing the server session and application context.

object_idint, optional

ID of the object, as returned by find_objects.

querystr, optional

Keywords to search for in API names. Case-insensitive; every word must match.

details_onlybool, default: True

With object_id, return only properties shown in the Details view, which are the settings a user normally edits. Set to False for every public API property.

name_containsstr, optional

With object_id, case-insensitive text that the property name or Details caption must contain.

include_methodsbool, default: False

With object_id, also return the public method signatures.

limitint, default: 30

With query, maximum number of matches to return, from 1 to 200.

Returns:
str

With object_id: JSON with object (ID, name, category, state, parent ID, API type), unit_system, and properties. Each property reports name, type, kind, writable, editable, and, where available, value, caption, display, read_only_in_details, enum_values, and range. editable means preview_property_change supports the property.

With query: JSON with ranked matches (name, type, kind, and signature), match_count, truncated, and types for a type named by the query.

tools.preview_property_change(ctx: fastmcp.server.Context, object_id: int, property_name: str, value: bool | int | float | str) → str#

Validate a property change and show its effect without applying it.

The preview reports the target object, the current value, the proposed value, and the validation result. A valid preview returns a single-use preview_token. Nothing in the model is changed: show the preview to the user and call apply_property_change only after they agree.

Values are checked strictly against the property type: booleans must be true or false, integers must fit the property range, enum values must be an exact member name, and quantities must be a string such as "10 [mm]" with a unit compatible with the current value.

Parameters:
ctxContext

MCP context containing the server session and application context.

object_idint

ID of the object, as returned by find_objects.

property_namestr

API property name, as returned by describe_api, such as ElementSize or NumberOfSteps.

valuebool, int, float, or str

New value. Use a string for enum members and quantities.

Returns:
str

JSON with target, current_value, proposed_value, validation (valid, errors, and warnings), and, when valid, no_change, preview_token, and expires_in_seconds.

tools.apply_property_change(ctx: fastmcp.server.Context, object_id: int, property_name: str, value: bool | int | float | str, preview_token: str) → str#

Apply a property change that was previewed with preview_property_change.

The change is applied only if the token matches the same object, property, and value, has not been used, has not expired, and the current value has not changed since the preview. Otherwise nothing is changed and the call fails. After applying, the value is read back from Mechanical. There is no automatic undo.

Parameters:
ctxContext

MCP context containing the server session and application context.

object_idint

ID of the object, exactly as previewed.

property_namestr

API property name, exactly as previewed.

valuebool, int, float, or str

New value, exactly as previewed.

preview_tokenstr

Token returned by preview_property_change. Each token works once.

Returns:
str

JSON with target, previous_value, the read-back value, readback_matches, and warnings. Errors use stale_preview when the preview is no longer valid.

tools.check_script(ctx: fastmcp.server.Context, script: str | None = None, file_path: str | None = None) → str#

Check a Mechanical script without running it.

Use this before run_python_script to catch mistakes early. The script is compiled, not run, by the scripting engine of the connected Mechanical, so syntax that the engine does not support (for example, f-strings in IronPython 2.7) is reported. Names such as Model.Mesh.ElementSize are then looked up in the live session to find misspelled or nonexistent API members. Lookups read properties but never call methods.

A passing check does not guarantee that the script succeeds: argument types, values, and the model state at run time are not validated.

Parameters:
ctxContext

MCP context containing the server session and application context.

scriptstr, optional

Script to check. Required when file_path is not provided.

file_pathstr, optional

Path to a local Python (.py) script file to check. Takes precedence over script when both are provided.

Returns:
str

JSON with valid, engine_syntax, python3_syntax, api_check (performed, checked_count, problems with line, chain, message, and suggestions, and unverified), and the connected product_version and python_engine.

tools.get_mechanical_logs(ctx: fastmcp.server.Context, source: str = 'messages', tail_lines: int = 200, contains: str | None = None, max_chars: int = 40000, analysis_index: int | None = None) → str#

Return recent log entries from the connected Mechanical instance.

This tool provides visibility into Mechanical session activity by reading either the application message list or solver output log file.

Parameters:
ctxContext

MCP context containing the server session and application context.

sourcestr, optional

Log source to read. Options are:

  • "messages" (default): Application messages (errors, warnings, info) from ExtAPI.Application.Messages.

  • "solve_log": Raw solver transcript from solve.out in the solver working directory, read on the Mechanical host.

tail_linesint, default: 200

Number of most recent lines to return.

containsstr, optional

Case-insensitive substring filter applied to each line.

max_charsint, default: 40000

Maximum character count for the returned log text.

analysis_indexint, optional

Analysis whose solve.out to read (0-based) when source is "solve_log". When None, the most recently written log is read.

Returns:
str

JSON string with log metadata and selected log text.

tools.REQUIRES_MECHANICAL_TAG = 'requires_mechanical'#
tools.logger#