chemscheme
by rjsky311
README.md
# ChemScheme
[](https://github.com/rjsky311/chemscheme/actions/workflows/ci.yml)
> Generate multi-step reaction schemes from SMILES, names, or natural language descriptions, with SVG/PNG rendering and ChemDraw CDXML interchange.

*SVG output for `tests/fixtures/sample_scheme_convergent.json`, shown as an image: `chemscheme draw tests/fixtures/sample_scheme_convergent.json -o scheme.svg`*
**ChemScheme** is a Python CLI + MCP server designed for chemistry researchers who need to create, validate, and render multi-step reaction schemes for publications. It combines RDKit for chemical validation and rendering, drawsvg for SVG composition, and Claude API for natural language intent parsing.
> **Status:** v0.1.0. Built March–April 2026; not under active development since
> April 2026. Not published on PyPI; install from source.
## Features
- **Multi-step scheme rendering** — SVG and PNG output with automatic layout (linear and convergent)
- **Four validation layers** — schema, chemistry (RDKit parsing, valence, stereo warnings), an optional reaction check, and step-to-step continuity
- **Compound name resolution** — local list of 112 reagent and material abbreviations (78 with stored SMILES; the rest resolve by name), then OPSIN, then PubChem
- **AI intent parsing** — Generate `scheme.json` from natural language descriptions via Claude API
- **ChemDraw interop** — CDXML export that opens in ChemDraw, and CDXML import; ChemScheme's own files round-trip with step links intact. Reversible and retro arrows are drawn in SVG and PNG only; CDXML gets a plain forward arrow.
- **MCP server** — Expose tools for AI agents via the Model Context Protocol
- **Convergent synthesis** — Graph-aware `consumes_step_ids` for branching and merging reaction pathways
## Installation
### From source
```bash
git clone https://github.com/rjsky311/chemscheme.git
cd chemscheme
pip install -e ".[dev]"
```
### Optional extras
```bash
pip install -e ".[png]" # CairoSVG for full PNG output
pip install -e ".[mcp]" # MCP server for AI agents
pip install -e ".[web]" # Local API and prototype web page (see Project Status)
pip install -e ".[ai]" # Claude API for natural language parsing
pip install -e ".[indigo]" # Indigo toolkit (optional renderer module; the CLI and MCP server use RDKit)
pip install -e ".[image]" # DECIMER for image-to-SMILES
```
### Supported platforms
- Python 3.13, tested in CI. Python 3.14 is experimental: CI runs it but
allows it to fail.
- Linux (Ubuntu) and Windows, tested in CI. macOS is tested locally only.
- RDKit 2024.x to 2026.03 (`rdkit<2026.9` in `pyproject.toml`).
## Quick Start
### 1. Create a scheme
Write a `scheme.json` file:
```json
{
"schema_version": "1",
"title": "Suzuki Coupling",
"steps": [
{
"id": "1",
"reactants": ["c1ccc(Br)cc1", "OB(O)c1ccccc1"],
"products": ["c1ccc(-c2ccccc2)cc1"],
"arrow_above": "Pd(PPh3)4, K2CO3",
"arrow_below": "DMF, 80 °C, 12 h",
"yield": "78%"
}
]
}
```
### 2. Validate
```console
$ chemscheme validate scheme.json
Valid scheme. (layers: schema, chemistry, continuity; skipped: reaction)
⚠ Reaction check skipped: no reaction predictor is configured, so products were not checked against their reactants
$ chemscheme validate scheme.json --json
{"status": "ok", "valid": true, "issues": [], "warnings": ["Reaction check skipped: no reaction predictor is configured, so products were not checked against their reactants"], "layers_checked": ["schema", "chemistry", "continuity"], "layers_skipped": ["reaction"], "reaction_steps_skipped": []}
```
`layers_checked` lists only the layers that ran. The reaction layer needs a
`ReactionPredictor` passed to `validate_scheme_json()` from Python; the CLI
and MCP server have none configured, so they list it under `layers_skipped`.
Warnings go to stderr. A test runs these commands and compares the output
with this block.
### 3. Render
```bash
chemscheme draw scheme.json -o output.svg
chemscheme draw scheme.json -o output.png # needs the [png] extra for a full render
```
### 4. Resolve compound names
```bash
chemscheme resolve "aspirin"
# CC(=O)Oc1ccccc1C(=O)O (source: pubchem, confidence: 0.85)
chemscheme resolve "NBS" --json
# {"status": "ok", "smiles": "O=C1CCC(=O)N1Br", "confidence": 0.95, "source": "local_alias", "warnings": []}
```
### 5. Generate from natural language (requires `ANTHROPIC_API_KEY`)
```bash
export ANTHROPIC_API_KEY=sk-ant-...
chemscheme ai "Suzuki coupling of bromobenzene with phenylboronic acid using Pd catalyst" -o scheme.json
```
### 6. Edit schemes
```bash
# Add a step
chemscheme edit scheme.json --add-step '{"id": "2", "reactants": ["c1ccc(-c2ccccc2)cc1"], "products": ["CC(=O)c1ccc(-c2ccccc2)cc1"], "arrow_above": "AcCl, AlCl3", "arrow_below": "CH2Cl2, 0 °C to rt"}'
# Remove a step
chemscheme edit scheme.json --remove-step "2"
```
### 7. ChemDraw interop
```bash
# Export to CDXML
chemscheme export scheme.json -o scheme.cdxml
# Import from CDXML
chemscheme import scheme.cdxml -o imported.json
```
Import reads each structure from its drawn atoms and bonds. ChemScheme's
exports also store the SMILES each structure was drawn from; if the drawing
no longer matches it (for example, after editing in ChemDraw), the drawing
is used and the import reports a warning.
## scheme.json Format
The intermediate format uses a graph-aware JSON structure:
| Field | Required | Type | Description |
|-------|----------|------|-------------|
| `schema_version` | Yes | string | Schema version (currently `"1"`) |
| `title` | No | string | Scheme title |
| `steps` | Yes | array | Reaction steps |
Each step:
| Field | Required | Type | Description |
|-------|----------|------|-------------|
| `id` | Yes | string | Unique step identifier |
| `reactants` | Yes | string[] | SMILES strings for reactants |
| `products` | Yes | string[] | SMILES strings for products |
| `arrow_above` | Yes | string or string[] | Reagents/conditions above the arrow |
| `arrow_below` | No | string or string[] | Conditions below the arrow |
| `yield` | No | string | Reaction yield |
| `reagents` | No | string[] | Reagent list |
| `solvents` | No | string[] | Solvent list |
| `temperature` | No | string or number | Reaction temperature |
| `time` | No | string or number | Reaction time |
| `atmosphere` | No | string | Atmosphere (e.g., N2, Ar) |
| `branch_label` | No | string | Branch identifier for parallel synthesis |
| `consumes_step_ids` | No | string[] | Step IDs consumed (for convergent synthesis) |
### Convergent Synthesis Example
4,7-Di(thiophen-2-yl)-2,1,3-benzothiadiazole, a common donor–acceptor
building block, from two branches joined by a Stille coupling:
```json
{
"schema_version": "1",
"title": "Convergent Stille Coupling",
"steps": [
{
"id": "1a",
"reactants": ["c1ccc2nsnc2c1"],
"products": ["Brc1ccc(Br)c2nsnc12"],
"arrow_above": "Br2, 48% HBr",
"arrow_below": "reflux",
"branch_label": "acceptor"
},
{
"id": "1b",
"reactants": ["c1ccsc1"],
"products": ["CCCC[Sn](CCCC)(CCCC)c1cccs1"],
"arrow_above": "1) n-BuLi, THF, −78 °C; 2) Bu3SnCl",
"branch_label": "donor"
},
{
"id": "2",
"consumes_step_ids": ["1a", "1b"],
"reactants": ["Brc1ccc(Br)c2nsnc12", "CCCC[Sn](CCCC)(CCCC)c1cccs1"],
"products": ["c1csc(-c2ccc(-c3cccs3)c3nsnc23)c1"],
"arrow_above": "2.2 equiv stannane, Pd(PPh3)4",
"arrow_below": "toluene, 110 °C"
}
]
}
```
Step 2 names both branches in `consumes_step_ids`; validation fails unless
each branch's product is one of step 2's reactants.
## MCP Server
ChemScheme exposes tools via the [Model Context Protocol](https://modelcontextprotocol.io/) for AI agent consumption.
### Tools
| Tool | Description |
|------|-------------|
| `draw_scheme` | Render a scheme.json to SVG or PNG |
| `validate_scheme` | Check a scheme's structures and the links between its steps |
| `resolve_name` | Resolve a chemical compound name to SMILES |
| `extract_image` | Recognize a structure image and return SMILES with confidence |
| `extract_text` | Turn an experimental-section paragraph into scheme steps |
| `generate_procedure` | Draft an experimental procedure from a scheme |
| `lookup_reagent`, `suggest_conditions` | Reagent lookup and typical conditions by reaction type |
| `add_user_reagent`, `remove_user_reagent`, `list_user_reagents` | Manage a personal reagent alias list |
### Running the MCP server
```bash
chemscheme-mcp
```
Or configure in your MCP client (e.g., Claude Desktop):
```json
{
"mcpServers": {
"chemscheme": {
"command": "chemscheme-mcp"
}
}
}
```
## Architecture
```
chemscheme/
cli.py # Click CLI (`chemscheme ...`)
mcp_server.py # FastMCP server (`chemscheme-mcp`)
models.py # SmilesResult, ValidationResult, RecognitionResult
domain_library.py # Reagent lookup and reaction-type suggestions
procedure_generator.py # scheme.json -> experimental procedure text
text_extraction.py # Experimental paragraph -> scheme.json steps
parsers/
name_resolver.py # Name -> SMILES (local alias, OPSIN, PubChem)
smiles_utils.py # SMILES canonicalization
ai_intent.py # Natural language -> scheme.json draft (Claude API)
structure_reader.py # MOL / SDF / CDX files -> SMILES
mathpix_client.py # Mathpix OCR client
validators/
layer1_chemistry.py # RDKit parsing, valence, stereo warnings
layer2_reaction.py # Optional product check through a ReactionPredictor
layer3_scheme.py # Step-to-step continuity
renderers/
rdkit_renderer.py # Default single-step renderer (RDKit drawing)
drawsvg_composer.py # Step SVG: molecules, arrow, conditions, labels
multi_step_renderer.py # Multi-step SVG / PNG / PDF / EPS
layout_engine.py # Step positions: linear, convergent, row wrap
themes.py # Journal themes (ACS, Nature, RSC, Wiley)
cdxml_writer.py # CDXML export and import
indigo_renderer.py # Optional Indigo renderer, not used by the CLI or MCP server
recognition/
ocsr.py # MolScribe, DECIMER, MolNexTR and Mathpix adapters
runner.py # Runs the OCSR tools as subprocesses or in Docker
cross_validator.py # Compares answers from several tools
lookup.py # Known-structure lookup (fingerprint search)
review.py # Confidence gate and human review queue
diagram.py # Reaction diagram parsing (RxnIM, RxnScribe)
conditions.py # Condition text from images (Claude Vision, EasyOCR)
pdf_extract.py # Figures from PDFs (PyMuPDF)
benchmark.py # OCSR benchmark against a ground-truth set
protocols.py, mocks.py # Recognizer interfaces and test doubles
editors/
scheme_editor.py # Add / remove steps without mutating the input
schema/
scheme_schema.py # scheme.json validation and atomic save
web/
app.py, bridge.py # Local authoring server (FastAPI) and SMILES <-> MOL bridge
static/ # Prototype page embedding the Ketcher demo
data/
reagent_aliases.json # Reagent and material abbreviations
reaction_patterns.json # Named reactions and typical conditions
lab_context.json # Lab preferences and style defaults
```
Rendering: the CLI, the MCP server and `render_scheme()` all use
`rdkit_renderer.render_step()`. RDKit draws each molecule, `drawsvg_composer`
builds the step SVG around it, and PNG output goes through CairoSVG when it is
installed (the `[png]` extra). Without it PNG falls back to a much simpler Pillow
drawing and warns, so use SVG or install the extra. `indigo_renderer.py` is an optional alternative
(the `[indigo]` extra) that nothing in the CLI or MCP server calls.
### Validation Layers
Four layers. Errors make the scheme invalid; warnings do not.
1. **Schema** — JSON structure, required fields, types, and `consumes_step_ids`
that point only to earlier steps.
2. **Chemistry** — every SMILES must parse and pass RDKit sanitization
(valence, aromaticity). Warnings for a stereo marker (`@`, `/`, `\`) that
RDKit drops because the atom or bond is not stereogenic (e.g.
`C[C@H](C)Cl`), and for a stereocenter or double bond with no
configuration (e.g. `CC(O)CC`).
3. **Reaction** — checks each step's products against a pluggable
`ReactionPredictor`. Runs only when one is passed to
`validate_scheme_json()`; otherwise listed under `layers_skipped`. Without
it, ChemScheme does not check that a product can form from its reactants.
4. **Continuity** — a linear step must use a product of the step it is drawn
after: the previous step of its branch, or with no branch label the step
before it in the list. Each step listed in `consumes_step_ids` must supply
one of the reactants. Compounds match by RDKit canonical SMILES, so a different
structure, stereoisomer, or salt form does not count as the same compound.
### Design Decisions
- **AI drafts, validators decide** — The `ai` command asks the Claude API for a draft `scheme.json`, SMILES included. The draft passes schema checks only; run `chemscheme validate` for the chemistry and continuity checks before using it
- **SmilesResult unified type** — Every name or SMILES lookup returns one frozen dataclass that records its source (local alias, OPSIN, PubChem). Its `confidence` is a fixed number per source, not a measured probability
- **Graph semantics** — `consumes_step_ids` supports convergent synthesis (OPV, NFA pathways)
- **Atomic writes** — Scheme JSON saves and CLI drawing output use temp-file-then-replace with Windows retry logic; CDXML export writes its file directly.
- **Thread safety** — Alias loading uses double-checked locking; the optional Indigo renderer serializes its calls with a lock
## Development
### Setup
```bash
pip install -e ".[dev,mcp,web,indigo]" # the extras CI installs
```
### Quality gate (run before committing)
```bash
ruff check . && ruff format --check . && mypy chemscheme/ && pytest -v
```
### Test suite
```bash
pytest -v # All tests: 1,423 pass, 7 skip
pytest -m "not visual" # What CI runs: 1,403 pass, 7 skip
pytest -m unit # Unit tests only
pytest -m chemistry # Chemistry-specific tests
pytest -m smoke # Environment verification
```
### Test markers
| Marker | Description |
|--------|-------------|
| `unit` | Fast, no external dependencies |
| `integration` | May use external services |
| `smoke` | Environment and dependency verification |
| `chemistry` | Chemistry-specific (SMILES, reactions) |
| `visual` | SVG golden file regression |
| `slow` | Tests exceeding 5 seconds |
Counts are with the `dev`, `mcp`, `web` and `indigo` extras. The 7 skipped
tests need PyMuPDF (5), CairoSVG (1) or a Mathpix key (1); without the
`indigo` extra, 4 more skip.
CI (GitHub Actions) runs `ruff`, `ruff format --check` and `mypy` on Ubuntu
with Python 3.13, then `pytest -m "not visual"` on Ubuntu and Windows with
Python 3.13 and on Ubuntu with Python 3.14 (experimental, allowed to fail),
then installs the built wheel and smoke-tests the CLI and MCP server on Ubuntu
and Windows. The visual tests compare rendered SVGs with reference files that
depend on the RDKit version, so they run only locally. macOS is tested only
locally.
## Project Status
Built in about five weeks (March 14 – April 19, 2026), then paused.
| Area | Status |
|-------|--------|
| Core: schema, rendering, four-layer validation, CLI, MCP, CDXML, name resolution | Done |
| Chemical interchange (charge, isotope, stereo) and drawsvg production renderer | Done |
| Publication annotations, convergent and L-shaped layouts, polymer brackets | Done |
| Journal themes (ACS, Nature, RSC, Wiley) | Done |
| Structure recognition from images and PDFs (OCSR ensemble in Docker, cross-validation, human review queue) | Done; real-tool accuracy depends on the Docker images you build |
| Reagent library, condition suggestions, text extraction, procedure drafts | Done |
| Local web API (conversion, recognition, scheme files) | Done |
| Web editor page | Prototype: it embeds the public Ketcher demo, but the canvas and the Save and Load buttons are not connected yet |
| PyPI release | Workflow written, not published |
## How It Was Built
ChemScheme was designed and directed by one synthetic chemist, Yu-Che Lin
(PhD, organic electronic materials). Yu-Che Lin set the chemistry rules and
acceptance criteria; Claude Code (Anthropic) wrote the code and tests; OpenAI
Codex and Google Gemini reviewed the plans and code at key phases. See
[docs/CASE_STUDY.md](docs/CASE_STUDY.md).
## License
MIT. See [LICENSE](LICENSE).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues