MoleditPy MCP Server Plugin

Expose MoleditPy to AI assistants via the Model Context Protocol (MCP).

Once running, any MCP-compatible client — Claude Desktop, Claude Code, Cursor, Windsurf, Zed, VS Code (Copilot), OpenAI Codex CLI, Google Antigravity, or any HTTP client — can query and control the molecular editor in real time.

Tests Test Coverage MoleditPy Downloads GitHub tag PyPI - mcp-gui-tester DOI

Repo: https://github.com/HiroYokoyama/moleditpy-mcp_server/

main


What you can do with this

Molecule editing and analysis

Ask an AI to load, modify, and analyze molecules entirely through conversation:

  • Load by name — “Load caffeine” → PubChem lookup → molecule appears in the editor
  • Query the current molecule — get SMILES, formula, MW, atom/bond tables, 3D coordinates
  • Edit atoms and bonds — add or remove bonds by atom index (edit_bonds, the Bond Editor way: coordinates kept, one undo step), or run arbitrary RDKit code via run_python
  • 3D visualization — trigger 2D→3D conversion, switch to 3D viewer, highlight specific atoms or bonds in color, fit/reset the camera
  • Reproducible figures — point the camera exactly (set_3d_camera, also along an atom-atom axis or straight at a ring face, with optional parallel projection), switch the display style (set_3d_style), overlay atom indices, and save a PNG into the sandbox (save_molecule_image, white or transparent background)
  • Measure and compare — distances, angles and dihedrals by atom index (measure_geometry); RMSD and a translucent overlay against another structure (compare_structures)
  • XYZ without dialogs — load XYZ text or files (including multi-frame trajectories) with an explicit charge or skip_chemistry, so the app’s charge prompt never blocks an AI call
  • Undo-safe editing — every change can push an undo checkpoint; the user can always revert

DFT / QM input file generation

Use the AI as a smart input file generator:

  • Generate ORCA, Gaussian, NWChem, … inputs from the current geometry
  • Write files directly to disk — the AI calls write_file_with_xyz_block (coordinates come straight from the live molecule) or write_text_file into a sandboxed directory you configure
  • Read files back — verify what was written, or load a computed result (.xyz, .log, …)
  • Organize jobs — list_directory, create subdirectories, delete obsolete files

Example prompt: “Generate an ORCA input for B3LYP/def2-TZVP geometry optimization of the current molecule and save it to opt.inp.”

Plugin authoring

The AI can read the MoleditPy source and write new plugins for you:

  1. get_plugin_dev_manual — fetch the full Plugin Development Manual V4 from the web
  2. find_files / grep_files with root: app_source — locate files and definitions in the installed moleditpy package
  3. get_app_source — read any source file (e.g. plugins/plugin_interface.py) to understand the exact API
  4. write_text_file (pointed at the plugin directory) — write the plugin code
  5. reload_plugins — activate the new plugin without restarting MoleditPy

Example prompt: “Write a MoleditPy plugin that adds a menu item to export the current molecule as a TURBOMOLE coord file.”

Scripting and automation

run_python lets the AI execute any Python on MoleditPy’s Qt main thread with full PluginContext access. Use it for one-off operations too complex for the built-in tools — RDKit workflows, batch atom edits, custom property calculations — and get stdout, stderr, and a return value back.


Installation

  1. Copy (or symlink) the mcp_server/ folder into your MoleditPy plugin directory:

    Platform Path
    Windows C:\Users\<You>\.moleditpy\plugins\mcp_server\
    Linux / macOS ~/.moleditpy/plugins/mcp_server/
  2. Restart MoleditPy (or choose Plugins → Reload All Plugins).

  3. Choose Plugins → MCP Server → Status & Settings… to start the server.

  4. Connect your MCP client. For Claude Code, one command registers the server for all your projects:

    claude mcp add --transport http -s user moleditpy http://127.0.0.1:7891/mcp
    

    Or register it for one project only by putting a .mcp.json in that project folder, then run claude there once and approve the server when prompted:

    {
      "mcpServers": {
        "moleditpy": { "type": "http", "url": "http://127.0.0.1:7891/mcp" }
      }
    }
    

    Pick one of the two: with both, the same server is configured twice. Check the connection with claude mcp get moleditpy (it should say Connected). Other clients are listed under Connecting MCP clients.


Usage

Starting the server

Open Plugins → MCP Server → Status & Settings…, set the port (default 7891), and click Start Server.

The dialog shows the live server URL and a ready-to-paste configuration snippet.

Protocol version

The MCP protocol selector in the same dialog chooses which revision of the protocol the server speaks:

Setting Meaning
Auto (default) Serves both eras on one port — an initialize handshake gets the classic session protocol, per-request metadata gets stateless 2026-07-28
Legacy only 2024-11-05 … 2025-11-25 handshake protocol; modern requests are refused with an UnsupportedProtocolVersion error
2026-07-28 only Stateless protocol exclusively: no session id, mirrored MCP-Protocol-Version / Mcp-Method / Mcp-Name headers are required and validated, initialize is refused

Restart the server after changing it. In the 2026-07-28 era the server implements server/discover (supported versions, capabilities, and natural-language usage instructions), marks every result resultType: "complete", returns ttlMs / cacheScope cache hints on tools/list, and reports header or version problems as 400 with JSON-RPC error codes -32020 / -32022.


Connecting MCP clients

The server implements MCP Streamable HTTP (POST /mcp) for both protocol eras: 2026-07-28 (stateless) and 2024-11-05 … 2025-11-25 (handshake).

Claude Desktop

Add the following to claude_desktop_config.json (replace the port if you changed it):

{
  "mcpServers": {
    "moleditpy": {
      "type": "streamable-http",
      "url": "http://127.0.0.1:7891/mcp"
    }
  }
}

Restart Claude Desktop. MoleditPy now appears as a connected tool server.

Claude Code (CLI)

Quickest: claude mcp add --transport http -s user moleditpy http://127.0.0.1:7891/mcp (all projects), or -s project to write a .mcp.json in the current folder. Equivalent configuration:

{
  "mcpServers": {
    "moleditpy": {
      "type": "http",
      "url": "http://127.0.0.1:7891/mcp"
    }
  }
}

Or set it per-project in .claude/settings.json inside your project folder.

Cursor

Add to ~/.cursor/mcp.json (global) or .cursor/mcp.json (project):

{
  "mcpServers": {
    "moleditpy": {
      "url": "http://127.0.0.1:7891/mcp"
    }
  }
}

Windsurf

Add to ~/.codeium/windsurf/mcp_config.json (Windows: %USERPROFILE%\.codeium\windsurf\mcp_config.json):

{
  "mcpServers": {
    "moleditpy": {
      "serverUrl": "http://127.0.0.1:7891/mcp"
    }
  }
}

Zed

Add to ~/.config/zed/settings.json (macOS: Zed → Settings…):

{
  "context_servers": {
    "moleditpy": {
      "url": "http://127.0.0.1:7891/mcp"
    }
  }
}

VS Code (GitHub Copilot)

Add to .vscode/mcp.json in your workspace (VS Code 1.101+):

{
  "servers": {
    "moleditpy": {
      "type": "http",
      "url": "http://127.0.0.1:7891/mcp"
    }
  }
}

OpenAI Codex CLI

Add to ~/.codex/config.toml (global) or .codex/config.toml (project):

[mcp_servers.moleditpy]
url = "http://127.0.0.1:7891/mcp"

Google Antigravity

Add to ~/.gemini/antigravity/mcp_config.json (Windows: %USERPROFILE%\.gemini\antigravity\mcp_config.json):

{
  "mcpServers": {
    "moleditpy": {
      "serverUrl": "http://127.0.0.1:7891/mcp"
    }
  }
}

curl / raw HTTP

You can call the server from any HTTP client. Example — list available tools:

curl -s -X POST http://127.0.0.1:7891/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | python -m json.tool

Call a tool:

curl -s -X POST http://127.0.0.1:7891/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_current_molecule","arguments":{}}}' | python -m json.tool

Health check:

curl http://127.0.0.1:7891/health

GUI tester

PyPI Python

main

A standalone PySide6 test client, mcp-gui-tester, is included as a separate installable package for interactive debugging. It connects to any MCP server speaking the Streamable HTTP transport, lists the available tools, generates a parameter input form from each tool’s inputSchema (with required/optional handling, JSON editors for array/object parameters, and enum dropdowns), and shows both the formatted result and the raw JSON-RPC response:

pip install mcp-gui-tester        # or: pip install -e mcp_gui_tester/ from this repo
mcp-gui-tester                    # defaults to http://127.0.0.1:7891/mcp
mcp-gui-tester --url http://localhost:9000/mcp

Host, port, endpoint path, and the protocol era (auto-detect / 2026-07-28 / legacy handshake) are editable in the GUI, so it can be pointed at other MCP HTTP servers too. It also shows each tool’s behaviour annotations (read-only / destructive / network), asks for confirmation before calling a destructive tool, and has a Server tab with the negotiated version, capabilities, and the server’s usage instructions. See mcp_gui_tester/README.md for details.

Auto-start

To start the server automatically every time MoleditPy launches, open Plugins → MCP Server → Status & Settings and check Auto-start server on launch.

Where MCP settings are saved

From version 2.1.0, all MCP settings are stored in mcp_server/settings.json inside the installed plugin folder. This includes the port, auto-start, protocol mode, authentication token, file I/O base directory, allowed extensions, and read-only folders. GUI and MCP-tool changes are saved there immediately. The Plugin Installer preserves this file when updating the plugin; release packages do not contain your settings.

On the first launch after upgrading, the plugin imports its existing values from MoleditPy’s shared app settings if the local settings.json is absent. The existing authentication token is retained, so configured clients keep working. The old app settings file and its MCP keys are not deleted. Once the local file exists, only it is read and written; the old keys are not used as fallbacks. If you delete the local file, the legacy import runs again. A malformed local file is reported as an error and is left untouched.

The settings file contains the authentication token. Keep it private and out of source control or shared plugin folders.

If another MoleditPy instance is already serving the configured port, starting (manually or on launch) is skipped and the dialog shows that it is running in another instance.

Reloading plugins stops the running server and starts it again with the reloaded code, so the port is never left held by the old copy.


AI Skill (SKILL.md)

The plugin ships a mcp_server/skills/moleditpy-mcp/SKILL.md that teaches AI agents how to use these tools well: always taking coordinates from the live molecule (never retyping them), checkpointing the undo stack after edits, configuring the file sandbox before writing, ready-made recipes for QM input generation and plugin authoring, and discovering/suggesting installable plugins.

Served over MCP (Claude Code 2.1.331 or later)

The server also serves the skill through the MCP Skills extension (skills/list, skills/get, resources/read, advertised in server/discover). A client that supports it picks the skill up from the running plugin, so it always matches the installed version; nothing needs copying. In Claude Code it appears as <server name>:moleditpy-mcp, e.g. moleditpy:moleditpy-mcp. The extension is a 2026-07-28 feature, so leave Protocol on auto or modern.

Copying the file (other clients)

Clients without the extension (Cursor, Codex, older Claude Code, …) still need a copy. Copy the skill directory into a skills directory, and copy it again after updating the plugin:

# Personal (all projects)
mkdir -p ~/.claude/skills
cp -r mcp_server/skills/moleditpy-mcp ~/.claude/skills/

# Or per-project
mkdir -p .claude/skills
cp -r mcp_server/skills/moleditpy-mcp .claude/skills/

The file is also inside the installed plugin folder (~/.moleditpy/plugins/mcp_server/skills/moleditpy-mcp/). Claude loads it automatically whenever a task involves the MoleditPy MCP tools. Other agent frameworks that support Anthropic-style skills (a SKILL.md with YAML frontmatter) can consume the same file.


Available MCP Tools

Molecule tools

Tool Description
get_current_molecule SMILES, formula, MW, atom/bond counts, 3D availability (for a structure loaded with distance-based bonds only: formula and weight from the atoms, no SMILES)
get_molecule_xyz 3D XYZ coordinate block (Element X Y Z per line)
get_atom_properties Per-atom: symbol, Z, charge, hybridization, Hs, radical electrons
get_bond_info Full bond table: endpoints and bond type (SINGLE/DOUBLE/TRIPLE/AROMATIC)
get_selected_atoms Indices and symbols of user-selected atoms
load_molecule_from_smiles Draw a molecule from a SMILES string (replaces the canvas; clear: false adds)
load_from_mol_block Load a molecule from a MOL/SDF block (replaces the canvas; clear: false keeps the 2D drawing)
load_molecule_by_name Look up by common/IUPAC name on PubChem and load (e.g. "aspirin"); replaces the canvas unless clear: false
show_xyz_in_viewer Display an XYZ block in the 3D viewer. charge (for ions) or skip_chemistry (distance-based bonds) answer the app’s charge prompt, and a d/f-block metal’s distance-bond confirmation is answered too, so no dialog blocks the call; frame picks one frame of a trajectory; the camera is re-fitted to the new molecule unless keep_camera
load_xyz_file Same as show_xyz_in_viewer, but reads an .xyz file from the sandbox — no pasting of coordinates; multi-frame files default to the last frame
get_mapped_smiles SMILES with atom indices embedded as map numbers + legend (find atom_index targets)
apply_reaction_smarts Modify the 2D molecule with a Reaction SMARTS transformation (optional anchor atom)
trigger_3d_conversion Run MoleditPy’s built-in 2D→3D optimizer (ETKDG/MMFF)
get_molecule_image Render the molecule to a PNG returned as an actual image — the 2D canvas or the 3D viewer (view: auto / 2d / 3d, width, height, atom_labels to overlay atom indices, background: a color or transparent)
save_molecule_image Write the same PNG into the file sandbox (path ending in .png, overwrite, background) — for reports and notes
get_3d_camera / set_3d_camera Read or set the 3D camera: position or direction (the side you look from), focal_point, view_up, fit, zoom; or by atoms — direction_atoms [i, j] (view along the i→j axis from j’s side), plane_atoms (look straight at the best plane of 3+ atoms, e.g. a ring), focal_atoms (look at their centroid); parallel_projection — makes figures reproducible
set_3d_style Switch the 3D style: ball_and_stick, cpk, wireframe, stick
edit_bonds Add and/or remove bonds by atom index pairs (add, remove, bond_type), as the Bond Editor plugin does: 3D coordinates kept, one undo step; an edit that breaks valence rules (an atom above its usual valence) is kept unsanitized and reported
measure_geometry Distances (2 atoms), angles (3) and dihedrals (4) by 0-based index, several per call
compare_structures RMSD against another structure with the same atom order (xyz_text or sandbox path, frame), Kabsch-aligned; heavy_atoms_only; overlay switches to the stick style and draws both, told apart by carbon color (current_color, overlay_color; other elements keep CPK colors); clear_overlay: true removes it and restores the style and colors
get_molecule_descriptors RDKit’s standard descriptor set in one call: canonical SMILES, formula, MW, exact mass, LogP, TPSA, formal charge, HBD/HBA, rotatable bonds, ring and atom/bond counts
hydrogens action: add adds explicit hydrogens (RDKit AddHs; 3D coordinates are generated for them when the molecule already has a conformer); action: remove strips them back to implicit (RDKit RemoveHs)
optimize_geometry Minimize the existing 3D conformer with MMFF94 or UFF — refines coordinates rather than generating them (force_field, max_iters)
set_atom_charge Set one atom’s formal charge by index; re-sanitized, and rejected if the result is not a valid structure
delete_atoms Delete atoms by index (highest first, so the caller’s other indices stay valid); re-sanitized
substructure_search Every SMARTS match in the molecule, as atom-index tuples (unique_matches to keep or collapse symmetry-equivalent hits)
compute_partial_charges Gasteiger partial charges per atom, computed on a private copy so the canvas is untouched (optional atom_indices filter)
set_color_override Color atoms (atom_colors) and bonds (bond_colors by index, atom_pair_colors by "i-j") in the 3D viewer; persists across redraws. reset (atoms / bonds / all) clears overrides first, in the same call
push_undo_checkpoint Push the current state onto MoleditPy’s undo stack
set_view_mode Switch the UI between 2D editing (2d) and the 3D viewer (3d)
check_chemistry Trigger MoleditPy’s valence-violation validation pass
refresh_view Redraw the 3D scene and sync the info panel, undo/redo state and title bar; fit_2d and reset_3d_camera options
clear_canvas Clear the 2D editor (undo-safe)
get_app_info One call for the app’s state: versions, the document (file, unsaved changes, 2D/3D view), plugin directory, file I/O sandbox, open dialogs, the count of “C++ object already deleted” errors, and the recovery snapshot path
close_dialogs Close open dialogs by rejecting them (Cancel/No, never an acceptance): modal and error dialogs by default, modeless windows with include_modeless, title filter
reset_document Snapshot the document as a project, clear it and load it back (file path and unsaved flag kept) — clears stale internal state such as repeated “already deleted” errors; the undo history restarts
restart_app Snapshot the document, close MoleditPy and start a new process that restores it and this server; the snapshot stays in ~/.moleditpy/mcp_recovery/ for a manual open if the app hangs
run_python Execute arbitrary Python on the Qt main thread with ctx access — see below

Plugin authoring tools

Tool Description
get_plugin_dev_manual Fetch the Plugin Development Manual V4 from the web
get_app_source Read a source file (optionally a start_line–end_line slice) or list a directory within the package
grep_files Regex search across the app source, the plugin directory, or the file sandbox — returns path:line: text, with glob, ignore_case, fixed_string, and context options
find_files List files matching a name glob in any of those trees
reload_plugins Re-scan and reload all plugins (activates freshly written plugins)
list_available_plugins Fetch the official plugin registry and list installable plugins (optional search filter)
open_plugin_installer Open the in-app Plugin Installer window to install a suggested plugin; if the installer plugin is absent, directs the user to the Plugin Explorer for a manual download

File I/O tools (sandboxed)

Tool Description
write_file_with_xyz_block Preferred for QM input generation — write a file composed as header + live XYZ coordinate block + footer, with element_style, atom_order, precision, and standard-XYZ-header options
write_text_file Write text to a file; auto-creates parent dirs; overwrite=false by default
read_text_file Read a file’s UTF-8 text content (≤ 4 MB); optional start_line / end_line slice. Relative to the base directory, or an absolute path inside a read-only folder
list_directory List files and subdirectories with sizes (base directory or a read-only folder)
delete_file Delete a file; requires explicit confirm=true
set_file_io_config Set the sandbox directory and/or update the extension allowlist — the user approves every change in a MoleditPy dialog
request_read_folder Ask for read-only access to a folder outside the base directory; MoleditPy shows a Yes/No dialog and only a Yes adds it

run_python — execute arbitrary Python

run_python lets an AI run any Python code on the Qt main thread with full access to MoleditPy’s PluginContext as ctx. Use it for complex RDKit operations, custom manipulations, or reading/pushing molecules back into the editor:

# Example: add an isotope label to atom 0 and reload
from rdkit import Chem

mol = ctx.current_molecule
mol.GetAtomWithIdx(0).SetIsotope(13)
ctx.current_molecule = mol
ctx.push_undo_checkpoint()
ctx.refresh_ui()
result = mol.GetNumAtoms()

stdout, stderr, and the value of result are returned to the AI. There are no extra sandbox restrictions beyond running inside MoleditPy’s process — treat it as a trusted power tool.

Security model

All file operations are restricted to a base directory you configure. Set it in Plugins → MCP Server → Status & Settings (File access tab → Read/write folder), or let the LLM request it via set_file_io_config:

Set the file I/O base directory to /home/you/dft_jobs

Widening access always needs you. When an AI calls set_file_io_config (base directory or extension list) or request_read_folder, MoleditPy shows a Yes/No dialog (default No) describing exactly what changes; nothing changes unless you press Yes. The MCP client cannot approve on your behalf.

Read-only folders. Besides the base directory you can allow folders that are only read: add them in the Status & Settings dialog (File access tab → Read-only folders), or approve an AI’s request_read_folder. Inside them read_text_file, list_directory, load_xyz_file and compare_structures accept absolute paths; writing and deleting stay confined to the base directory.

The Status monitor separates Server, File access, and Client configuration. Read-only folders appear in a table with an availability status. Select a row to read or copy its path in the same editable box used for adding folders. Type/paste a folder and click Add…, or clear the box and click Add… to browse. Remove selected revokes only selected folders; Clear all… asks before revoking all read-only folders. Missing folders remain listed so their permissions can be removed. A path inside the read/write folder stays writable even if it is also listed as a read-only folder.

Client-approved folders appear while the dialog is open. Start failures and invalid path entries remain visible in the dialog. Copied URLs and configuration snippets use the actual running port, or the selected port before starting.

Security guarantees:

  • Path traversal blocked — ../../etc/passwd is rejected; every path is resolved and must stay within the base directory (reads: or within an approved read-only folder; absolute paths are accepted only there).
  • Extension allowlist — only extensions on the allowed list can be written/read/deleted. Defaults cover common DFT/QM formats (.inp, .xyz, .gjf, .mol, .pdb, .txt, .json, …). Use set_file_io_config to customise.
  • Overwrite protection — write_text_file refuses to replace existing files unless overwrite=true is passed explicitly.
  • Deletion requires confirmation — delete_file requires confirm=true in the same call.
  • Size limit — reads and writes are capped at 4 MB.
  • No browser access — requests from a web page (a non-loopback Origin, or a DNS-rebinding Host) are refused with HTTP 403, so a site you visit cannot drive the server.

Typical DFT workflow example

“Generate an ORCA input file for the current molecule using B3LYP/def2-TZVP and save it to ethanol_opt.inp.”

The LLM will:

  1. Call get_current_molecule (and trigger_3d_conversion if there is no 3D geometry yet).
  2. Call write_file_with_xyz_block with path="ethanol_opt.inp", header=["! B3LYP def2-TZVP Opt", "* xyz 0 1"], and footer=["*"] — the coordinate block is inserted directly from the live molecule, so nothing is retyped.
  3. Optionally call read_text_file to confirm what was written.

Typical plugin authoring workflow

“Write a MoleditPy plugin that adds a menu item to copy the current SMILES to the clipboard.”

The LLM will:

  1. Call get_plugin_dev_manual to read the full API.
  2. Call find_files with root: app_source to map the source, then get_app_source "plugins/plugin_interface.py" for the exact contract.
  3. Call get_app_info to find the plugin directory.
  4. Call set_file_io_config to point the sandbox at the plugin directory.
  5. Call write_text_file with path="smiles_copy/__init__.py" and the generated plugin code.
  6. Call reload_plugins to activate it — the new menu item appears immediately.

Architecture

mcp_server/
├── __init__.py   — Plugin entry point (initialize, MCPServerPlugin)
├── bridge.py     — Thread-safe Qt signal bridge (server thread → Qt main thread)
├── server.py     — HTTP server implementing MCP Streamable HTTP transport
└── ui.py         — Status & Settings dialog

Thread safety — All PluginContext calls must occur on the Qt main thread. MCPBridge achieves this by emitting a QueuedConnection signal from the server thread; the main thread executes the operation and signals completion via a threading.Event.

No extra dependencies — Uses only Python’s built-in http.server and threading.


Development

# Install test dependencies
pip install pytest pytest-cov

# Run tests
pytest tests/ -v

# Run with coverage
pytest tests/ --cov=mcp_server --cov-report=term-missing

Tests run fully headlessly — no GUI, no RDKit, no MoleditPy installation required.


Compatibility

Requirement Version
MoleditPy ≥ 5.0.0, < 6.0.0
Python 3.11+
MCP protocol 2026-07-28 and 2024-11-05 … 2025-11-25 (Streamable HTTP, selectable)

No extra pip dependencies — uses Python’s built-in http.server and threading.

Authentication (1.8.6 and later)

Every MCP POST requires Authorization: Bearer <token>, including initialize, discovery, and tool calls. Open MCP Server > Status & Settings and copy the client configuration again after upgrading: the generated snippets include the token. The token is generated randomly and saved in this user’s plugin settings, so it remains valid after a restart. Keep connection snippets private; avoid committing them to shared project configuration. The GUI tester’s custom headers field accepts {"Authorization": "Bearer <token>"}.

Loopback binding and Origin/Host checks still apply. A local TCP port is reachable by other OS users, so those checks alone cannot authorize privileged Python and file tools. The health endpoint remains public and never returns the token.

Licensing scope

First-party code in this migration is LGPL-3.0-or-later. See LICENSE, COPYING and dependency/provenance terms. Third-party components and historical releases retain their own terms.