Driving MoleditPy via MCP

MoleditPy exposes its editor over a local MCP HTTP server (default port 7891, started from Plugins → MCP Server inside the app). All tool calls run on the app’s Qt main thread and act on the molecule the user currently sees.

What MoleditPy is

MoleditPy is a desktop molecular editor (PySide6 + RDKit + PyVista) for preparing quantum-chemistry / DFT calculations. Its core workflow:

  1. 2D editing — the user draws or loads a molecule on a 2D canvas (the primary editing surface; bonds, charges, and stereochemistry are edited here). Loading tools (load_molecule_from_smiles, load_molecule_by_name, load_from_mol_block) target this canvas.
  2. 2D → 3D conversion — trigger_3d_conversion builds a 3D structure (RDKit ETKDG embedding + force-field optimization) and switches to the 3D viewer. Only after this do 3D coordinates exist.
  3. 3D viewing/analysis — a PyVista-based viewer shows the conformer; plugins (and these MCP tools) read coordinates, color atoms/bonds, and export geometry from here.
  4. Input generation & plugins — the geometry feeds input generators for Gaussian, ORCA, GAMESS, xTB, etc.; a large official plugin ecosystem covers analysis, import/export, and visualization.

The 2D canvas and the 3D viewer hold SEPARATE representations. Most coordinate-reading MCP tools (including current molecule state) see the 3D side — so with a freshly drawn or freshly loaded 2D molecule, coordinate tools report “no 3D data” until trigger_3d_conversion runs. Loading tools (load_molecule_from_smiles, load_molecule_by_name, load_from_mol_block) act on the 2D side only — convert afterwards. Exception: apply_reaction_smarts auto-converts its product to 3D by default (its convert_to_3d argument, default true), so chained edits and follow-up coordinate reads work without an extra conversion step.

Core rules

  1. Never retype coordinates. To create any file that contains the current molecule’s geometry (QM input files, .xyz exports), use write_file_with_xyz_block — it takes the coordinate block directly from the live molecule. Compose the rest of the file with its header/footer arguments. Only use write_text_file for files that contain no molecular coordinates.
  2. Check state before acting. Start a session with get_app_info: one call reports the document (file, unsaved changes, 2D/3D view), the file I/O sandbox, the plugin folder, any open dialogs and the stale-object error count. get_current_molecule tells you if a molecule is loaded and whether 3D coordinates exist. If not, trigger_3d_conversion first — coordinate tools error without a 3D conformer.
  3. Checkpoint AFTER edits. Call push_undo_checkpoint after you finish modifying the molecule with run_python (the dedicated edit tools, apply_reaction_smarts included, push their own checkpoint) so the change lands in the undo history — the system snapshots the current state and only records it if it differs from the previous checkpoint. Calling it before the edit does nothing.
  4. Loading replaces by default. load_molecule_from_smiles, load_molecule_by_name and load_from_mol_block clear the 2D canvas first (undoable, like clear_canvas). Pass clear: false only when the user wants the new molecule added beside the existing one.
  5. Search before reading. grep_files answers “where is this defined / used” in one call — the app source (root: "app_source"), the user’s plugins (root: "plugins"), or the sandbox (root: "files"). Read the hit with get_app_source / read_text_file and start_line/end_line rather than pulling in whole files.
  6. File I/O is sandboxed. All file tools need a base directory. If a file tool errors with “base directory is not configured”, ask the user for a directory and call set_file_io_config — do not guess a path. Extensions are allowlisted; add new ones via the same tool. Every change is approved by the user in a MoleditPy dialog. To only read files elsewhere, call request_read_folder (absolute path + reason); after a Yes, read tools take absolute paths inside it. If the user declines, do not ask again for the same thing.

Tool map

Goal Tools
Inspect state get_app_info (start here), get_current_molecule, get_molecule_xyz, get_atom_properties, get_bond_info, get_selected_atoms, get_mapped_smiles, get_app_info, get_molecule_descriptors (MW / LogP / TPSA / HBD / HBA / rings in one call), substructure_search (SMARTS → atom indices), compute_partial_charges (Gasteiger)
See it get_molecule_image — returns a real PNG of the 2D canvas or 3D viewer. Use it to check a structure, a highlight or a reaction result yourself instead of asking the user what they see. atom_labels=true overlays atom indices.
Figures set_3d_style (stick shows partial bonds and overlays best), set_3d_camera (direction = the side you look from, or direction_atoms [i, j] / plane_atoms / focal_atoms; view_up, zoom, parallel_projection) then save_molecule_image (PNG into the sandbox; background: white or transparent). get_3d_camera records a view to reuse. Contacts that distance-based bonding misses (long, partial or forming bonds): edit_bonds.
Measure / compare measure_geometry (distance / angle / dihedral by index), compare_structures (RMSD + optional overlay: stick style, carbons colored per structure; then compare_structures with clear_overlay: true restores the view)
Edit with RDKit hydrogens (action: add / remove), set_atom_charge (index from get_mapped_smiles), delete_atoms, optimize_geometry (MMFF/UFF, refines an existing conformer — trigger_3d_conversion generates one). Each pushes its own undo checkpoint. Prefer these over hand-written run_python.
Load molecules load_molecule_by_name (PubChem), load_molecule_from_smiles, load_from_mol_block, show_xyz_in_viewer / load_xyz_file (pass charge for ions or skip_chemistry — never leave the app’s charge dialog to the user; frame for trajectories), clear_canvas
Edit edit_bonds (add/remove bonds by atom index, coordinates kept, one undo step), apply_reaction_smarts (SMARTS transforms), run_python (arbitrary RDKit / PluginContext code), push_undo_checkpoint, check_chemistry
3D view trigger_3d_conversion, set_view_mode (2d / 3d), set_color_override (atom_colors, atom_pair_colors "i-j", bond_colors; reset first in the same call; persists across redraws), refresh_view (redraw + sync UI; fit_2d, reset_3d_camera options)
Files (sandboxed) write_file_with_xyz_block (preferred for inputs), write_text_file, read_text_file (start_line/end_line), list_directory, delete_file, set_file_io_config (user approves; current setup is in get_app_info), request_read_folder (read-only access, user approves)
Search grep_files (regex over app_source / plugins / files), find_files (name glob over the same roots)
Plugin authoring get_plugin_dev_manual, find_files / grep_files (root: app_source), get_app_source, reload_plugins; the plugin folder is in get_app_info
Recovery close_dialogs (rejects, never accepts), reset_document, restart_app — see Troubleshooting
Plugin discovery list_available_plugins (official registry, optional search), open_plugin_installer

When the user needs functionality MoleditPy lacks (an input generator, analyzer, exporter, …), check list_available_plugins first — an official plugin may already exist. Suggest it, then call open_plugin_installer so the user can install it in-app; never download plugin code yourself. If the installer is unavailable, point the user at the Plugin Explorer for a manual download: https://hiroyokoyama.github.io/moleditpy-plugins/explorer/

Recipe: generate a QM input file

  1. get_current_molecule — confirm loaded; note formula for sanity.
  2. If no 3D coords: trigger_3d_conversion.
  3. get_app_info — if the file I/O base directory is not configured, ask the user, then set_file_io_config.
  4. write_file_with_xyz_block with:
    • path: e.g. "opt/job.inp" (parents auto-created)
    • header: keywords + charge/multiplicity as a normal multi-line string (e.g. ORCA: "! B3LYP def2-TZVP Opt\n* xyz 0 1"); an array of lines also works if your transport escapes newlines
    • footer: closing section if the format needs one (ORCA: "*")
    • options if the format demands them: element_style (symbol default → C x y z; atomic_number → 6 x y z; symbol_and_number → C 6.0 x y z for GAMESS $DATA), atom_order (0-based indices, reorder or subset), precision, xyz_header+comment for standard .xyz files.
  5. read_text_file the result back and show the user the final content.

For multi-file jobs, repeat step 4 per file; use overwrite: true only when the user asked to replace.

Recipe: write a MoleditPy plugin

  1. get_plugin_dev_manual for the V4 API contract.
  2. get_app_source on plugins/plugin_interface.py for exact PluginContext signatures — do not invent API from memory. When you need a method or signal the manual doesn’t cover, grep_files the app source for it (e.g. pattern: "def add_menu_action") instead of guessing; find_files locates the module first if you don’t know it.
  3. Take the plugin folder from get_app_info, then point set_file_io_config at it and write_text_file the plugin (single .py with initialize(context) and the PLUGIN_* constants).
  4. reload_plugins to activate without restarting.
  5. If the new/edited plugin does not appear or still runs the old code after reload_plugins, don’t keep re-reloading — see Troubleshooting.

Troubleshooting: dialogs, stale state, reload problems

Pick the lightest fix that matches the symptom, and check the result with get_app_info / get_current_molecule afterwards.

Symptom Fix
A tool errors that a dialog is open, or get_app_info lists a modal dialog Error dialogs: close_dialogs freely. Any other dialog: tell the user what it asks; close it with close_dialogs only with their OK (it always answers Cancel/No).
Repeated “Internal C++ object … already deleted” error dialogs, or get_app_info shows a non-zero stale-object count reset_document: snapshot, clear and reload the document, keeping file path and unsaved flag.
The errors come back after reset_document, reload_plugins left old or half-loaded code, or the app misbehaves for no clear reason restart_app: snapshot, close the app, start a new one that restores the document and this server.
The app is frozen and no tool answers Ask the user to close MoleditPy. If you have a shell, start moleditpy <snapshot> with the recovery snapshot path from an earlier get_app_info; otherwise ask the user to open that file.

Rules:

  1. Ask the user before reset_document or restart_app. Both clear the undo history; a restart also closes plugin windows and stops running calculations. Neither touches the document if its snapshot cannot be taken.
  2. Don’t retry the failing call first. A stale-object error does not go away by itself; recover, then retry once.
  3. After restart_app, the connection drops for a few seconds. Wait, then call get_current_molecule to confirm the document came back. If the app refused to close (a running calculation, a plugin’s question), it is still running unchanged.
  4. If the problem persists after a restart, it is a genuine bug — help the user report it instead of retrying (main app: https://github.com/HiroYokoyama/python_molecular_editor/issues).

run_python escape hatch

Runs on the Qt main thread with the PluginContext available as ctx (import RDKit yourself); stdout/stderr are captured, and assigning to result returns a value (e.g. result = ctx.current_molecule.GetNumAtoms()). Use it for anything the dedicated tools cannot do (batch atom edits, custom descriptors). Keep snippets short; after mutating the molecule call refresh_view (or ctx.refresh_ui() / ctx.refresh_3d_view() in the snippet) and then push_undo_checkpoint. Never keep or touch the editor’s Qt graphics items directly — that is how stale-object errors start; read and change the molecule through ctx.current_molecule.