The ``session_tools.py`` module =============================== .. py:module:: ansys.geometry.mcp.tools.session_tools Summary ------- .. py:currentmodule:: session_tools .. tab-set:: .. tab-item:: Functions .. list-table:: :header-rows: 0 :widths: auto * - :py:obj:`~get_session_script` - Get recorded session commands as a reusable PyAnsys Geometry Python script. * - :py:obj:`~get_backend_status` - Get the current status of the product backend. * - :py:obj:`~run_python` - Perform any geometry/CAD operation that has no dedicated MCP tool. * - :py:obj:`~create_design` - Create a new design in the product backend. * - :py:obj:`~get_design_info` - Get an inventory of the active design, including objects inside components. * - :py:obj:`~file_operation` - Import a geometry file or export the active design. * - :py:obj:`~run_iron_python` - Run Discovery/SpaceClaim scripting API code on the geometry backend. .. tab-item:: Attributes .. list-table:: :header-rows: 0 :widths: auto * - :py:obj:`~logger` - 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 ----------------- 1. Define a Python function with type-annotated parameters. 2. Add a NumPy-style docstring. The summary line becomes the tool description. visible to the AI assistant. 3. Decorate it with ``@app.tool()``. 4. 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 ------------- .. py:function:: 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 operations Parameters ---------- ctx : Context 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. .. py:function:: get_backend_status(ctx: fastmcp.server.Context) -> str Get the current status of the product backend. Parameters ---------- ctx : Context MCP request context (injected automatically). Returns ------- str Status message describing whether the product is connected. .. py:function:: run_python(ctx: fastmcp.server.Context, code: str, timeout: int = 300, no_output_timeout: int = 300) -> str :async: 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.core`` code and run it here. Choose a dedicated tool whenever one exists. Use ``run_iron_python`` for 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`` (the ``Modeler``) and ``design`` are 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, so ``print()`` the values you need. Look up the API with ``suggest_api`` and ``get_api_details`` before writing the code, and use the documented signatures and imports as given without re-checking them. Introspect with ``dir()`` or ``help()`` 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 ---------- ctx : Context MCP request context (injected automatically). code : str PyAnsys Geometry Python code to execute in the persistent session. timeout : int, default: 300 Maximum time in seconds the code may run before it is abandoned. no_output_timeout : int, 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``, and ``error`` keys. On failure, read ``error``/``stderr``, correct the code, and retry rather than reporting the operation as impossible. If execution succeeds but synchronizing the server-side design fails, ``success`` remains true and ``refresh_error`` describes the synchronization failure. Do not rerun successful geometry operations because of ``refresh_error``. .. py:function:: create_design(ctx: fastmcp.server.Context, design_name: str) -> str Create a new design in the product backend. Parameters ---------- ctx : Context MCP request context (injected automatically). design_name : str Name of the design to create. Returns ------- str Result message indicating success or failure. .. py:function:: 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_alive`` flag 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_entities`` to discover object IDs and component paths. Parameters ---------- ctx : Context MCP request context (injected automatically). Returns ------- str Information about the design, or an error message if retrieval fails. .. py:function:: 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 include ``scdocx``, ``dsco``, ``pmdb``, ``step``, ``iges``, ``x_t``, ``xmt_txt``, ``stride``, and reader formats such as ``CATIA``, ``Creo``, ``NX``, ``JT``, ``SOLIDWORKS``, ``Solid Edge``, ``Inventor``, ``Rhino``, and ``AutoCAD``. Use ``operation="export"`` to save the active design in ``fmd``, ``step``, ``iges``, ``scdocx``, ``dsco``, ``parasolid_text``, or ``parasolid_bin`` format. Use ``file_path`` to specify the exact export filename, or ``folder`` to use the design name as the filename. Do not pass both. Parameters ---------- ctx : Context MCP request context (injected automatically). operation : Literal["import", "export"] Whether to import a file or export the active design. file_path : str, 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 ``folder`` for export. file_format : str, default: None Export format. Options are ``"fmd"``, ``"step"``, ``"iges"``, ``"scdocx"``, ``"dsco"``, ``"parasolid_text"``, and ``"parasolid_bin"``. This parameter is required for export. folder : str, 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. mode : str, 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_names : bool, default: False Whether to import the names of bodies and curves. import_curves : bool, default: False Whether to import curves. import_coordinate_systems : bool, default: False Whether to import coordinate systems. import_named_selections : bool, default: True Whether to import named selections. cleanup_bodies : bool, 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. .. py:function:: 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 ``script`` and ``file_path``. When NOT to use this tool: to execute PyAnsys Geometry API code. Use ``run_python`` instead. 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``, ...), use ``file_operation`` with ``operation="import"``. Do not write a temporary script file: pass Discovery/SpaceClaim code as ``script``. **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 the ``run_python`` session (or vice versa). **Passing arguments** ``args`` values must all be strings. The script receives them as a dictionary of strings named ``argsDict`` and is responsible for converting them, for example ``radius = MM(int(argsDict["radius"]))``. Pass ``{"radius": "1"}``, never ``{"radius": 1}``. Omit ``args`` when the script takes no arguments. **Returning values** To get values back, the script must assign a dictionary named ``result``, for example ``result = {"numBodies": numBodies}``. A script that does not define ``result`` returns 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``, or ``visualize`` before relying on previously reported names, IDs, or counts. Parameters ---------- ctx : Context MCP request context (injected automatically). file_path : str, 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``. args : dict[str, str], default: None String-valued arguments exposed to the script as ``argsDict``. script : str, default: None Discovery/SpaceClaim script source. Mutually exclusive with ``file_path``. Returns ------- str | dict[str, str] On success, the script's ``result`` dictionary with string values (empty if the script defined no ``result``) is returned. On failure, a plain string message is returned. Check the returned type. A ``str`` always means the script did not run, and the message should be reported to the user rather than retried unchanged. .. py:data:: logger