The session_tools.py module#
Summary#
Get recorded session commands as a reusable PyAnsys Geometry Python script. |
|
Get the current status of the product backend. |
|
Perform any geometry/CAD operation that has no dedicated MCP tool. |
|
Create a new design in the product backend. |
|
Get an inventory of the active design, including objects inside components. |
|
Import a geometry file or export the active design. |
|
Run Discovery/SpaceClaim scripting API code on the geometry backend. |
Description#
MCP session tools for PyAnsys Geometry-MCP.
Each function decorated with @app.tool() is exposed as an MCP tool.
The ctx parameter provides access to the app context (and thus
to the live product instance and command history).
How to add a tool#
Define a Python function with type-annotated parameters.
Add a NumPy-style docstring. The summary line becomes the tool description. visible to the AI assistant.
Decorate it with
@app.tool().Access the product instance:
app_context = ctx.fastmcp._lifespan_result instance = app_context.product_instance
Notes#
Import this module in __main__.py (already done) to register all tools
with the server before it starts.
Module detail#
- session_tools.get_session_script(ctx: fastmcp.server.Context) str#
Get recorded session commands as a reusable PyAnsys Geometry Python script.
The tool returns a formatted Python script containing the recorded backend connection setup and commands in execution order, not a command list or Markdown. To replay the script, install PyAnsys Geometry (
ansys-geometry-core) and ensure access to the recorded backend and any referenced files. Replaying repeats the recorded geometry changes. The script includes only operations stored in command history. It excludes backend script-file operationsParameters#
- ctxContext
MCP request context (injected automatically).
Returns#
- str
Formatted Python source, or an empty string if no commands were recorded.
Raises#
- ValueError
If recorded commands cannot be formatted as valid Python.
- session_tools.get_backend_status(ctx: fastmcp.server.Context) str#
Get the current status of the product backend.
Parameters#
- ctxContext
MCP request context (injected automatically).
Returns#
- str
Status message describing whether the product is connected.
- async session_tools.run_python(ctx: fastmcp.server.Context, code: str, timeout: int = 300, no_output_timeout: int = 300) str#
Perform any geometry/CAD operation that has no dedicated MCP tool.
Run PyAnsys Geometry API code to perform the operation.
This is the general-purpose fallback tool. When the user asks for a modeling, query, or modification action (such as fillet, chamfer, shell, measure, pattern) and no other tool matches it, do NOT answer that it is unsupported. Write the equivalent
ansys.geometry.corecode and run it here. Choose a dedicated tool whenever one exists. Userun_iron_pythonfor Discovery/SpaceClaim scripting API code or an existing script file. Never write a temporary file to run a few statements.The session is persistent, so variables defined by one call stay available to the next.
instance(theModeler) anddesignare predefined. Import anything else explicitly. Bodies, faces, and edges are reached through the design tree (design.bodies[0].faces[0].edges) and edits are methods on those objects. Only stdout is returned, soprint()the values you need. Look up the API withsuggest_apiandget_api_detailsbefore writing the code, and use the documented signatures and imports as given without re-checking them. Introspect withdir()orhelp()only for something the documentation does not cover, or after a documented call raises an error.The code runs in a separate process that is connected to the same geometry service the other tools use, so bodies they created are immediately available here, and bodies created here are immediately visible to them. After successful execution, the server-side design cache is synchronized.
Parameters#
- ctxContext
MCP request context (injected automatically).
- codestr
PyAnsys Geometry Python code to execute in the persistent session.
- timeoutint, default: 300
Maximum time in seconds the code may run before it is abandoned.
- no_output_timeoutint, default: 300
Maximum time in seconds the code may run without producing output before it is abandoned.
Returns#
- str
JSON string with
success,stdout,stderr, anderrorkeys. On failure, readerror/stderr, correct the code, and retry rather than reporting the operation as impossible. If execution succeeds but synchronizing the server-side design fails,successremains true andrefresh_errordescribes the synchronization failure. Do not rerun successful geometry operations because ofrefresh_error.
- session_tools.create_design(ctx: fastmcp.server.Context, design_name: str) str#
Create a new design in the product backend.
Parameters#
- ctxContext
MCP request context (injected automatically).
- design_namestr
Name of the design to create.
Returns#
- str
Result message indicating success or failure.
- session_tools.get_design_info(ctx: fastmcp.server.Context) str#
Get an inventory of the active design, including objects inside components.
Report counts of components, bodies, named selections, materials, coordinate systems, datum points, planes and lines, beams, beam profiles, design points, and design curves (including construction lines created as side effects of patterns, revolves, and similar operations). Component-owned objects are counted throughout the hierarchy, not just at the design root. Deleted components and objects with an
is_aliveflag set to false are excluded. Named selections, materials, and beam profiles are design-level collections.Use this to check what exists in the design, find leftover construction geometry, and as a final inventory check before exporting or saving. Use
list_entitiesto discover object IDs and component paths.Parameters#
- ctxContext
MCP request context (injected automatically).
Returns#
- str
Information about the design, or an error message if retrieval fails.
- session_tools.file_operation(ctx: fastmcp.server.Context, operation: Literal['import', 'export'], file_path: str | None = None, file_format: str | None = None, folder: str | None = None, mode: str = 'open', import_names: bool = False, import_curves: bool = False, import_coordinate_systems: bool = False, import_named_selections: bool = True, cleanup_bodies: bool = False) str#
Import a geometry file or export the active design.
Use
operation="import"to open a geometry file as a new design or insert it into the active design. Supported extensions includescdocx,dsco,pmdb,step,iges,x_t,xmt_txt,stride, and reader formats such asCATIA,Creo,NX,JT,SOLIDWORKS,Solid Edge,Inventor,Rhino, andAutoCAD.Use
operation="export"to save the active design infmd,step,iges,scdocx,dsco,parasolid_text, orparasolid_binformat. Usefile_pathto specify the exact export filename, orfolderto use the design name as the filename. Do not pass both.Parameters#
- ctxContext
MCP request context (injected automatically).
- operationLiteral[“import”, “export”]
Whether to import a file or export the active design.
- file_pathstr, default: None
Path of the file to import or the exact output path for export, including its extension. For a shattered assembly import, give the path of the assembly file. Referenced files in the same folder are included automatically. Required for import; mutually exclusive with
folderfor export.- file_formatstr, default: None
Export format. Options are
"fmd","step","iges","scdocx","dsco","parasolid_text", and"parasolid_bin". This parameter is required for export.- folderstr, default: None
Export directory. The design name and format-specific extension form the filename. If omitted along with
file_path, use the current working directory.- modestr, default:
"open" How to import the file. When
"open"is used, the active design is closed and the file is opened as a new design. Use"insert"to add the file into the current active design as a new design. Use"insert"to add the file into the current active design as a new component.- import_namesbool, default: False
Whether to import the names of bodies and curves.
- import_curvesbool, default: False
Whether to import curves.
- import_coordinate_systemsbool, default: False
Whether to import coordinate systems.
- import_named_selectionsbool, default: True
Whether to import named selections.
- cleanup_bodiesbool, default: False
Whether to simplify geometry and clean up topology on import.
Returns#
- str
Result message describing the imported or exported file, or an error message.
- session_tools.run_iron_python(ctx: fastmcp.server.Context, file_path: str | None = None, args: dict[str, str] | None = None, script: str | None = None) str | dict[str, str]#
Run Discovery/SpaceClaim scripting API code on the geometry backend.
Use this tool to execute Discovery/SpaceClaim script text or an existing script file (for example “run C:/scripts/make_flange.py” or “replay this .scscript”). Provide exactly one of
scriptandfile_path.When NOT to use this tool: to execute PyAnsys Geometry API code. Use
run_pythoninstead. That tool runs the PyAnsys Geometry API (instance,design, …) in a persistent session, while this tool runs a different language surface entirely. To load a CAD/geometry file (.scdocx,.step,.iges,.x_t, …), usefile_operationwithoperation="import". Do not write a temporary script file: pass Discovery/SpaceClaim code asscript.Script language
The script must be written against the Discovery/SpaceClaim scripting API, not the PyAnsys Geometry API. PyAnsys Geometry objects (
Modeler,Sketch,instance,design) are NOT available inside the script, and script variables do not leak into therun_pythonsession (or vice versa).Passing arguments
argsvalues must all be strings. The script receives them as a dictionary of strings namedargsDictand is responsible for converting them, for exampleradius = MM(int(argsDict["radius"])). Pass{"radius": "1"}, never{"radius": 1}. Omitargswhen the script takes no arguments.Returning values
To get values back, the script must assign a dictionary named
result, for exampleresult = {"numBodies": numBodies}. A script that does not defineresultreturns an empty dictionary even though it ran successfully.Side effects
The script might create or modify the active design on the backend. Those changes are not mirrored into this server’s in-process design state or command history, so after a script that edits geometry, refresh your view with
get_design_info,list_entities, orvisualizebefore relying on previously reported names, IDs, or counts.Parameters#
- ctxContext
MCP request context (injected automatically).
- file_pathstr, default: None
Path to the script file, including its extension. The path must be readable by the machine running this MCP server. Use an absolute path when possible, since relative paths are resolved against the server’s working directory. Mutually exclusive with
script.- argsdict[str, str], default: None
String-valued arguments exposed to the script as
argsDict.- scriptstr, default: None
Discovery/SpaceClaim script source. Mutually exclusive with
file_path.
Returns#
- str | dict[str, str]
On success, the script’s
resultdictionary with string values (empty if the script defined noresult) is returned. On failure, a plain string message is returned.Check the returned type. A
stralways means the script did not run, and the message should be reported to the user rather than retried unchanged.
- session_tools.logger#