Skip to main content
Glama
MALeitch

live-ketcher-mcp

by MALeitch
README.md
# live-ketcher-mcp

MCP server that connects AI assistants to a **live Ketcher window**, the
open-source web-based chemical structure editor. Draw, edit, and organize
structures directly in the canvas you have open.

**Status: Tier 1 + Tier 2 underway.** Transport (Phase 0) is done.
Twenty-two tools are live and verified end to end through a real
`mcp.call_tool` round trip against a real Ketcher v3.12.0 instance:
`ketcher_get_document_state`, `ketcher_diff_since_last_check`,
`ketcher_find_duplicates`, `ketcher_insert_structure`,
`ketcher_export_structure`, `ketcher_get_properties`,
`ketcher_transform_structure`, `ketcher_check_warnings`,
`ketcher_list_atoms`, `ketcher_add_atom`, `ketcher_edit_atom`,
`ketcher_edit_bond`, `ketcher_remove`, `ketcher_get_stereochemistry`,
`ketcher_set_bond_stereo`, `ketcher_set_enhanced_stereo`,
`ketcher_move_structure`, `ketcher_get_layout`, `ketcher_arrange_grid`,
`ketcher_make_arrow`, `ketcher_make_plus`, `ketcher_list_arrows`. See
[`ROADMAP.md`](ROADMAP.md) for the full scope and tool-by-tool port map,
and [`AGENTS.md`](AGENTS.md) for the transport internals and everything
that only surfaced once a real server and real tools existed — including
three corrections: `aromatize()`/`dearomatize()` are documented in
Ketcher's own API reference but don't actually exist on this build,
`setMolecule()` recenters the WHOLE document to a canonical viewport
position on every write (confirmed: absolute coordinates are never
preserved, only offsets between structures survive, exactly), and that's
the actual mechanism behind the small sibling-position drift noted
earlier.

Unlike its sibling project [`live-chemdraw-mcp`](https://github.com/MALeitch/live-chemdraw-mcp),
this needs no commercial license and no Windows: Ketcher is Apache 2.0 and
runs in a browser.

## Why this design

Ketcher exposes a real JavaScript API (`getKet`, `setMolecule`, `layout`,
`calculate`, `getSmiles`/`getMolfile`/`getCDXml`/`getInchi`, and OCR via
`recognize`). That means editing is a **document round trip**: read KET
JSON, transform it in Python, write it back. There is no imperative object
model to fight, so most tools are pure functions over JSON and are unit
testable without a browser.

Three findings from a live prototype against Ketcher v3.12.0 shaped the
architecture (details in `ROADMAP.md` section 6b):

1. `setMolecule()` **pushes onto the undo stack** rather than clearing it.
   AI edits are undoable, one tool call per undo entry.
2. Round trips preserve coordinates (to ~1e-6), selection, and atom
   ordering.
3. Writing back a **subset** of the document silently deletes everything
   omitted. The transport enforces read-all / write-all so tools cannot get
   this wrong.

## Layout

```
ketcher_connector/
  transport/   Playwright bridge to a live Ketcher page
    connection.py  launch/attach a visible browser running Ketcher
    document.py    read_document/apply_transform, the whole-document rule
    identity.py    stable claude-* ids via content hash, with rebind() for
                   self-initiated edits (see AGENTS.md item 1 under rule 6)
    internals.py   quarantined below-API access (undo/redo/selection)
    worker.py      dedicated thread owning the Playwright session
    convert.py     hidden scratch page: representation <-> KET fragment,
                    layout(), calculate() -- isolated from the live canvas
  bridge/      KET round-trip document surgery: get_document_state,
               diff_since_last_check, find_duplicates, insert/export_
               structure, get_properties, transform_structure
               (action='clean' only), check_warnings, list_atoms,
               add/edit_atom, edit_bond, remove, get/set_bond_stereo,
               set_enhanced_stereo, move_structure, get_layout,
               arrange_grid, make_arrow, make_plus, list_arrows
  domain/      pure logic, no editor coupling, pytest-covered
    ket_merge.py   splice/replace/centroid/remove_ref/arrow_node/
                   plus_node helpers for merging or removing a fragment
                   or annotation without disturbing the rest
    ket_atoms.py   pure atom/bond mutation (add/edit/remove/stereo),
                   including index-renumbering on removal
    ket_warnings.py   extracts valence warnings from calculate()'s own
                      error-string-in-place-of-a-number behavior
    dedup.py, diff.py, layout_math.py   ported unchanged from
      live-chemdraw-mcp -- fed KET-derived data instead of CDXML-derived
      data (layout_math's grid_positions/Box/find_overlaps power
      arrange_grid without any changes to that module at all)
    _cdxml_port_pending/   ported but CDXML-coupled, see AGENTS.md
tools/         thin MCP tool definitions
tests/         domain tests, run with no browser required
server.py      FastMCP stdio entry point
test_smoke_visual.py   live transport + bridge smoke test, real Ketcher
```

## Setup

```powershell
python -m venv .venv
.venv\Scripts\python -m pip install -e .
.venv\Scripts\python -m playwright install chromium
```

Register in `%APPDATA%\Claude\claude_desktop_config.json`:

```json
"mcpServers": {
  "ketcher": {
    "command": "C:\\path\\to\\live-ketcher-mcp\\.venv\\Scripts\\python.exe",
    "args": ["C:\\path\\to\\live-ketcher-mcp\\server.py"]
  }
}
```

Restart the Claude desktop app. The server launches its own visible browser
window running Ketcher — no separate install needed beyond the Playwright
Chromium binary above.

## Testing

```bash
python -m pytest                       # pure domain logic, no browser
python test_smoke_visual.py            # live transport check, visible window
python test_smoke_visual.py --headless # live transport check, no window
```

The `pytest` suite is pure logic against fakes and fixtures — no browser, no
Ketcher instance, no network. `test_smoke_visual.py` is the live
counterpart: it drives a real Ketcher instance and checks the properties
documented in `ROADMAP.md` section 6b and `AGENTS.md` (undo behavior,
whole-document write safety, identity stability) against the real app, not
just against the transport code in isolation.

## Provenance

The `domain/` modules and their tests are ported from `live-chemdraw-mcp`,
which is MIT licensed and by the same author. They were chosen because they
carry no editor coupling: caption association, panel-box violation
detection, layout math, SMARTS-based substructure matching, derivative
enumeration, HRMS text generation, and IUPAC naming are all independent of
which editor renders the result.

## License

[MIT](LICENSE). Ketcher itself is Apache 2.0 and is not bundled here.