The tools.py module#
Summary#
Check Mechanical status and non-sensitive MCP session diagnostics. |
|
Check if Mechanical is installed on the system. |
|
Execute a Python script inside Mechanical. |
|
Launch a new Mechanical instance. |
|
Connect to an existing Mechanical instance. |
|
Disconnect from the connected Mechanical instance. |
|
List all Mechanical instances running on the local machine. |
|
List files in the Mechanical working directory. |
|
Upload a file to the Mechanical instance. |
|
Download a file from the Mechanical instance. |
|
Download the connected Mechanical project’s files as one operation. |
|
Clear the Mechanical database. |
|
Return the working directory of the connected Mechanical instance. |
|
Get information about the current model in Mechanical. |
|
Capture a screenshot of the current Mechanical view. |
|
Execute Python code in the persistent Python session for data processing. |
|
Create a custom plot using Matplotlib in the persistent Python session. |
|
Save the current Mechanical project. |
|
Open an existing Mechanical project file. |
|
Solve the specified analysis in Mechanical. |
|
Export results from the solved analysis. |
|
Return solved result values as structured data. |
|
Find objects in the Mechanical Outline tree and return their stable IDs. |
|
Describe an object, or search the Mechanical API, of the connected release. |
|
Validate a property change and show its effect without applying it. |
|
Apply a property change that was previewed with |
|
Check a Mechanical script without running it. |
|
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_diagnosticstool.- Parameters:
- ctx
Context MCP context containing the server session and application context.
- ctx
- Returns:
strJSON 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:
strStatus 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, andGraphicsentry points.Provide either an inline
scriptstring or afile_pathpointing to a local Python file. Whenfile_pathis given, its contents are read and executed inside Mechanical.- Parameters:
- ctx
Context MCP context containing the server session and application context.
- script
str,optional The Python script to execute inside Mechanical. Required when
file_pathis not provided.- file_path
str,optional Path to a local Python script file whose contents are executed inside Mechanical. Takes precedence over
scriptwhen both are provided.
- ctx
- Returns:
strScript 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_mechanicalfunction. 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 (includingrun_python_script,screenshot, andsave_project).It always starts a new process; use
connect_to_mechanicalto attach to a running instance. Launching is refused when the server’s environment setsPYMECHANICAL_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:
- ctx
Context MCP context containing the server session and application context.
- exec_file
str, default:None path to the Mechanical executable. If
None, the executable matchingversionis used, or PyMechanical’s default installation whenversionis alsoNone.- port
int, default:None gRPC port for Mechanical to listen on. If
None,10000is used.- batch
bool|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.
- version
str, 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. IfNone, PyMechanical’s default installation (the saved path or the newest installed release) is used.- transport_mode
str, default:None gRPC transport mode for the launched instance. Options are
auto,insecure,mtls, andwnua. WhenNoneorauto, PyMechanical applies the platform default.
- ctx
- Returns:
strLaunch 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_mechanicaltool. Once connected, additional tools become available to interact with it (includingrun_python_script,screenshot, andsave_project).- Parameters:
- ctx
Context MCP context containing the server session and application context.
- port
int, default: 10000 gRPC port where Mechanical is listening.
- ip
str, default: “127.0.0.1” IP address where Mechanical is running.
- transport_mode
str, default:None gRPC transport mode. Options are
"auto","insecure","mtls", and"wnua". WhenNoneor"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".
- ctx
- Returns:
strConnection 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_mechanicalis shut down. An instance attached withconnect_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:
- ctx
Context MCP context containing the server session and application context.
- ctx
- Returns:
strDisconnection 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:
strFormatted 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:
- ctx
Context MCP context containing the server session and application context.
- ctx
- Returns:
strList 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.
- 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:
- ctx
Context MCP context containing the server session and application context.
- file_name
str 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 bylist_filesare also accepted.- target_dir
str,optional Local directory to save the downloaded file. If
None, the current directory is used.
- ctx
- Returns:
strDownload 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:
- ctx
Context MCP context containing the connected Mechanical instance.
- extensions
list[str] |None,optional Optional file extensions to include, such as
["mechdb", "png"]. When omitted, downloads all project files supported by PyMechanical.- target_dir
str|None,optional Local directory to receive the downloaded files. Uses the current directory when omitted.
- ctx
- Returns:
strJSON 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_mechanicalto end the session.- Parameters:
- ctx
Context MCP context containing the server session and application context.
- ctx
- Returns:
strClear 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:
strAbsolute 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:
- ctx
Context MCP context containing the server session and application context.
- max_items
intorNone, 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_objectscalls over an unlimited response.
- ctx
- Returns:
strJSON string containing model information. Includes
project,model,geometry,mesh(counts plus the active mesh metric),analyses_count,named_selections,materials,unit_system,analyses, andboundary_conditions.collection_inforeports total and returned counts and truncation per list. Geometry includes body counts byGeometryTypeand 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:
- ctx
Context MCP context containing the server session and application context.
- view_type
str, 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.
- ctx
- 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
ExtAPIorModel), use the ‘run_python_script’ tool instead.- Parameters:
- ctx
Context MCP context containing the server session and application context.
- code
str 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.- timeout
int, default: 60 Maximum time in seconds to allow for code execution.
- ctx
- Returns:
strExecution 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_scriptto export the data to a file. Then use this tool to create the visualization.- Parameters:
- ctx
Context MCP context containing the server session and application context.
- plot_code
str Python code to create the plot. You should use
matplotlib.pyplot. For Matplotlib, the code should create the figure or plot but not callplt.show(). Use thesave_matplotlib_plot()helper function to return the plot.- plot_type
str, default:"matplotlib" Type of plot. Options are
"matplotlib"and"pyvista".- timeout
int, default: 60 Maximum time in seconds for plot generation.
- ctx
- 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_pathis 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:
- ctx
Context MCP context containing the server session and application context.
- file_path
str, default:None Full path for saving the project (Save As). The path should end with a
.mechdbextension. The path is resolved on the connected Mechanical instance, which may be a different machine than the MCP server. IfNone, the project is saved in the current location.
- ctx
- Returns:
strSave 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:
- ctx
Context MCP context containing the server session and application context.
- file_path
str 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.
- ctx
- Returns:
strOpen 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:
- ctx
Context MCP context containing the server session and application context.
- analysis_index
int, default: 0 Index of the analysis to solve (0-based). The default,
0, corresponds to the first analysis.- wait
bool, default:True Whether to block until the solve finishes. When
False, the solve is started and the tool returns immediately. The reportedstatusthen reflects the solver state at that moment rather than the final outcome.
- ctx
- Returns:
strJSON 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:
- ctx
Context MCP context containing the server session and application context.
- analysis_index
int, default: 0 Index of the analysis to export results from (0-based). Use the same index that was passed to
solve_analysis.- result_type
str, default:"all" - Type of result to export. Options are
"all","deformation","stress", "strain", or a specific result object name.
- Type of result to export. Options are
- export_format
str, default:"png" Export format. Use
"png"for images,"txt"for text data, or"both"for images and text.- output_dir
str, 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. Usedownload_fileordownload_projectto copy the files locally.
- ctx
- Returns:
strJSON 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_analysisto 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:
- ctx
Context MCP context containing the server session and application context.
- analysis_index
int,optional Restrict the summary to a single analysis (0-based). When
None, every analysis in the model is reported.
- ctx
- Returns:
strJSON string with one entry per analysis, each listing its result objects with their
stateand their minimum, maximum, and average values and units. Values arenullunless 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_idvalues withdescribe_apiandpreview_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:
- ctx
Context MCP context containing the server session and application context.
- name_contains
str,optional Case-insensitive text that the object name must contain.
- category
str,optional DataModelObjectCategoryname, such asForce,FixedSupport,Body, orEquivalentStress. Case-insensitive.- parent_id
int,optional Search below this object only. By default the whole project is searched.
- max_depth
int,optional Number of levels below the start object to search. By default all levels are searched.
- limit
int, default: 100 Maximum number of objects to return, from 1 to 1000.
match_countalways reports the full number of matches.- offset
int, default: 0 Number of filtered matches to skip in Outline order. Follow
next_offsetuntil null to retrieve all matches, including lists larger than 1000. Keep filters unchanged; restart ifresult_fingerprintchanges.
- ctx
- Returns:
strJSON with
objects(object_id,name,category,state,path,depth, andchild_count),match_count,truncated,category_countsfor every object searched, and the connectedproduct_versionandpython_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_idorquery. 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 beforepreview_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.Memberquery 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:
- ctx
Context MCP context containing the server session and application context.
- object_id
int,optional ID of the object, as returned by
find_objects.- query
str,optional Keywords to search for in API names. Case-insensitive; every word must match.
- details_only
bool, default:True With
object_id, return only properties shown in the Details view, which are the settings a user normally edits. Set toFalsefor every public API property.- name_contains
str,optional With
object_id, case-insensitive text that the property name or Details caption must contain.- include_methods
bool, default:False With
object_id, also return the public method signatures.- limit
int, default: 30 With
query, maximum number of matches to return, from 1 to 200.
- ctx
- Returns:
strWith
object_id: JSON withobject(ID, name, category, state, parent ID, API type),unit_system, andproperties. Each property reportsname,type,kind,writable,editable, and, where available,value,caption,display,read_only_in_details,enum_values, andrange.editablemeanspreview_property_changesupports the property.With
query: JSON with rankedmatches(name,type,kind, andsignature),match_count,truncated, andtypesfor 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 callapply_property_changeonly after they agree.Values are checked strictly against the property type: booleans must be
trueorfalse, 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:
- ctx
Context MCP context containing the server session and application context.
- object_id
int ID of the object, as returned by
find_objects.- property_name
str API property name, as returned by
describe_api, such asElementSizeorNumberOfSteps.- value
bool,int,float,orstr New value. Use a string for enum members and quantities.
- ctx
- Returns:
strJSON with
target,current_value,proposed_value,validation(valid,errors, andwarnings), and, when valid,no_change,preview_token, andexpires_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:
- ctx
Context MCP context containing the server session and application context.
- object_id
int ID of the object, exactly as previewed.
- property_name
str API property name, exactly as previewed.
- value
bool,int,float,orstr New value, exactly as previewed.
- preview_token
str Token returned by
preview_property_change. Each token works once.
- ctx
- Returns:
strJSON with
target,previous_value, the read-backvalue,readback_matches, andwarnings. Errors usestale_previewwhen 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_scriptto 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 asModel.Mesh.ElementSizeare 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:
- Returns:
strJSON with
valid,engine_syntax,python3_syntax,api_check(performed,checked_count,problemswith line, chain, message, and suggestions, andunverified), and the connectedproduct_versionandpython_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:
- ctx
Context MCP context containing the server session and application context.
- source
str,optional Log source to read. Options are:
"messages"(default): Application messages (errors, warnings, info) fromExtAPI.Application.Messages."solve_log": Raw solver transcript fromsolve.outin the solver working directory, read on the Mechanical host.
- tail_lines
int, default: 200 Number of most recent lines to return.
- contains
str,optional Case-insensitive substring filter applied to each line.
- max_chars
int, default: 40000 Maximum character count for the returned log text.
- analysis_index
int,optional Analysis whose
solve.outto read (0-based) whensourceis"solve_log". WhenNone, the most recently written log is read.
- ctx
- Returns:
strJSON string with log metadata and selected log text.
- tools.REQUIRES_MECHANICAL_TAG = 'requires_mechanical'#
- tools.logger#