← Files Molecular Structure ViewerARCHIVED FILE

README.md

28.3 KB · Sep 30, 2026 · 23:00 UTC

↓ Download file

# Molecular Structure Viewer

Visualize and interact with molecular structures in Codex.

## Open A Structure

- Click a supported file in the Codex workspace tree to open the native rich preview.
- Ask Codex to open a supported local structure to render the viewer inline in chat.
- Ask `Show me an example protein structure` or `Show me a generic protein` to open the bundled GFP structure offline, without a download or workspace copy.
- Use **Open viewer** inside the viewer to move the same live view to the right pane.
- Use **Return to chat** to move it back without losing camera, representation, focus, or selection state.

Opening or interacting with the viewer does not automatically add molecular context to chat. Ask a relevant question in chat, and Codex can list, read, or search current live scene documents by range or in full. `structure.get_context` remains a compact overview. Reads retain focus/selection, molecular/assembly identities, revisions, and loaded-data coverage; they do not claim unimported source data. Native previews and chat-opened views support the same document reads and pure molecular queries. When several viewers could match your question, Codex resolves which one you mean; `structure.list_viewers` recalls previously read sessions, and **Ask about selection** identifies a viewer opened manually.

`structure.read_source` separately reads source content when the viewer has access, preserving whether it is original file bytes or a native reader's decompressed representation. Source content stays distinct from the current edited scene and is not uploaded by a read.

## Starter Examples

The three shipped starters use compact, stable RCSB inputs and tell distinct stories. Each downloads its input into the active workspace before opening exactly one viewer.

1. **Quantify an oncoprotein interface**

   > Open RCSB 1YCR once; analyze 4 Å MDM2–p53 contacts and buried area, label p53 Phe19/Trp23/Leu26, and report methods.

   This uses geometry and bounded solvent-accessible-surface sampling to connect the p53 hotspot residues to the MDM2 binding cleft. Buried area is a coordinate-derived structural measure, not a binding-energy estimate.

2. **Compare an enzyme's open and closed conformations**

   > Open RCSB 4AKE once; add 1AKE to the same viewer, align chain A, color teal/magenta, show AP5, and report RMSD/TM-scores.

   Both adenylate-kinase structures stay in one viewer. The overlay makes the AP5-associated domain closure visible while preserving the alignment method and scores.

3. **Create a provenance-bearing GFP figure**

   > Open RCSB 1EMA once; style and label its chromophore; save a versioned 1600×1200 PNG to structure-viewer/gfp.png with sidecar.

   Versioned publication never overwrites an existing artifact or sidecar. The output path remains workspace-relative, and the sidecar records the source digest, canonical scene, renderer, dimensions, and artifact digest.

The exact source snapshots, result ranges, workload budgets, and qualification handoff are packaged in `examples/starter-examples.json`. Density, trajectory, related-data, project-restore, and MP4 workflows remain documented capabilities rather than overloading these three starters.

## Molecular Workspace

The **Structure** inspector keeps molecules, chains, ligands, named selections, measurements, density maps, and saved scenes beside the molecular canvas. Its **Components** rows use one **Actions** menu containing familiar **Action · Show · Hide · Label · Color** operations, while density-map rows expose only their genuine **Action · Show · Hide** operations, so routine molecular operations do not require another conversation turn. A map can evaluate the exact current selection, correlate with another loaded map, or change visibility; full map styling remains in the Workbench. The sequence ribbon above the canvas supports selecting and highlighting multiple residues. Chat previews offer **Open viewer** to move the same structure into the full viewer. In narrow panes, **Show controls** opens the inspector below the canvas; the command bar and task-oriented Workbench reveal additional detail when needed.

Show or hide the Structure inspector, sequence ribbon, measurement overlays, command bar, Workbench, or Render panel. Choose whether clicking the structure picks one atom, its residue, its chain, or its complete molecular object. Codex can adjust every one of these workspace controls in the same viewer without changing or deleting molecular coordinates. The Workbench and Render panel never compete for the same drawer, and opening Render does not automatically create or save an image.

- **Action** focuses, selects, measures, analyzes, aligns, or manages the chosen molecular object. Save a named selection or scene, extract an exact selected structure, create a solvent-free copy, or rename a chain only in an explicitly named new copy; the original source never changes.
- **Show** adds cartoon, surface, connected bond-cylinder sticks, atom-sphere balls and sticks, or another representation without erasing the surrounding protein; **Show only** replaces representations only when explicitly requested.
- **Hide** changes visibility without deleting molecular data.
- **Label** adds, sizes, or removes genuinely distinct atom, residue, or chain annotations that remain correct in both the interactive viewer and rendered images or movies.
- **Color** applies conventional element coloring or chain, residue, property, and explicit color schemes.

A scientifically useful active-site view preserves the complete protein cartoon while showing selected residue or ligand side chains as connected sticks with conventional atom colors and unobtrusive labels. Multiple loaded molecular objects can be genuinely superposed by structure, sequence, or paired atoms; the resulting RMSD, aligned count, and available alignment scores distinguish an actual fit from an unaligned visual overlay. Named scenes, camera changes, measurements, maps, and object visibility participate in the same reversible workspace history. Codex can perform every enabled graphical action through the same bounded, authenticated, revision-guarded molecular controls, and can additionally coordinate structural queries, analyses, alignments, publication renders, and explicit exports.

The optional command bar supports a safe molecular command and selection vocabulary, including selectors such as `chain A+C`, `resi 19+23+26`, `resn HEM`, `name CA+CB`, and `byres (organic around 4)`, plus actual object alignment, camera clipping, and distance/angle/dihedral measurements. It cannot run Python, shell commands, scripts, or arbitrary code. The bundled [workspace action guide](examples/MOLECULAR_WORKSPACE.md) documents the complete object controls, selection dialect, scientific examples, and agent equivalents.

Residue solvent-accessible surface area is calculated in its complete molecular environment, not from an isolated residue. A protein-residue report excludes crystallographic waters from its output while retaining them in the complete solvent-occluding environment. Absolute exposure is reported in square ångströms (Ų); relative exposure is a separately labeled percentage normalized to residue-specific Tien observed maxima and is valid only for the standard 1.4 Å solvent probe. A nonstandard probe still supports absolute exposure, but cannot produce a valid Tien percentage. Unknown residue types have no invented relative percentage, and percentages can exceed 100 when a residue is more exposed than its observed reference. A threshold of 50 Ų is not equivalent to a threshold of 50%.

## RCSB-style inspection and export

The molecular canvas and sequence ribbon occupy the main view; scientific controls live in the right inspector, without a separate top toolbar. **Controls** always reopens the inspector. **Codex** host actions live in its footer, or at the canvas edge when it is closed. Whole-structure display settings are under **Components**, and the Workbench and command console are under **Advanced tools**. **Measurements** is the sole measurement interface; Codex retains the residue-distance and ligand-contact calculation tools from the retired panel.

The sequence ribbon's Structure, Mode, Entity, Chain, and Layout controls are shared with Codex, including **Show known sequence** for a same-structure polymer whose source supplies residue identities. `UNK` remains `UNK`; changing these filters never selects atoms or changes the structure. Exact chain and assembly-copy checks prevent silent retargeting after reconstruction. Ribbon filter preferences are session-only and are not saved in project manifests.

Drag across the ribbon to select a range, including ligands and wrapped rows. In both the ribbon and 3D canvas, **Shift-click** selects a sequence range within one polymer chain, **Ctrl/Command-click** adds or removes individual picks, and **Ctrl/Command-Shift-click** adds a range. Both views share the selection and range anchor. A plain 3D click keeps the normal focus action and anchors the next range. Selecting one atom marks its ribbon residue as partially selected without selecting the rest of that residue.

The inspector brings the RCSB-style workflows into the same editable scene, with corresponding Codex tools rather than separate, unsynchronized controls:

- **Structure** chooses a source model, biological assembly, and dynamic bonds. **Components** exposes all 18 canonical representations, 14 presets, detailed appearance and color options, and computed interactions. Whole-workspace presets and scoped component styling remain distinct, reversible operations.
- **View** controls camera helpers, lighting, clipping, sampling, stereo, and postprocessing. Local PNG/JPEG images and six matching square skybox faces are admitted from the active source's authenticated workspace, not arbitrary paths or URLs. Their identities and image budgets are checked again on history, project restore, and rendering. Codex uses the shared related-data browser and `structure.load_background` for the same workflow.
- **Measurements** includes saved selection labels, principal-axis orientation guides, and best-fit planes alongside distances, angles, and dihedrals. Guides retain exact atom identities, update with transforms and trajectory frames, and report when a removed or replaced source invalidates them.
- **Structure Motif Search** searches public PDB assemblies for geometrically similar arrangements of 2–10 explicitly identified public residues. Choose geometry tolerances and residue exchanges, then inspect paged matches and RMSD. A geometric match is not evidence of shared biological function.
- **Density** discovers actual experimental map channels for an explicit public accession. Loading a map saves a bounded, new BinaryCIF and provenance beside the opened source before applying it to the scene; a saved file and an applied map are reported separately. Local map loading and detailed contour/style controls remain available.
- **Quality Assessment** uses genuine embedded metrics or a matching public wwPDB validation report, including supported confidence, error, geometry, and clash information. Bounded PAE regions retain exact residue identities and can select the corresponding residues in 3D; missing cells are shown as unavailable, not zero. **Assembly Symmetry** uses matching public assembly records for supported axes, cages, and cluster colors. Unavailable metrics are not invented or replaced with B-factors.
- **Export Models** saves all loaded atoms or the selected subset as separate mmCIF or BinaryCIF model members in a ZIP, with source categories and an identity manifest. **Export Geometry** saves the visible rendered scene as GLB, binary STL, OBJ+MTL ZIP, or USDZ, retaining supported transforms and colors. The Workbench still offers scene JSON, selected PDB/mmCIF/BinaryCIF, and result CSV exports.

Public lookups require an explicit public accession and do not upload local structure files. A manually requested public density box sends its box coordinates to PDBe; Codex must not derive those bounds from private structures without consent. Map acquisition needs source-bound publication authority; model requests also need an active workspace-read root. It is limited to 16 MiB and 2,097,152 voxels per channel. Structured exports are limited to 16 MiB and use the existing no-overwrite workspace save workflow with a neighboring provenance sidecar. Geometry additionally has a 64 MiB expansion limit; a whole complex can exceed it even at low visual quality. Unsupported visible objects, clipping, or budget overruns stop export instead of silently omitting geometry. Choose a smaller visible scope or simpler representation explicitly before retrying. STL does not support colors.

Native image-background allocations have a per-viewer-document budget of 32 MiB encoded bytes, 128 MiB decoded RGBA/mip storage, and 128 faces, including failed loads and export reloads. At the limit, the viewer explains that you must close and reopen it to load more backgrounds; ordinary viewing and foreground-only exports remain available. Native-file hosts also need explicit image-resource admission support, otherwise the feature reports unavailable.

See the [capability and model-tool map](examples/CAPABILITY_MATRIX.md#rcsb-workspace-capabilities) for the exact agent routes and limits. These workflows do not change the three starters' separate clean-host qualification status.

## Supported Files

- PDB text coordinates: `.pdb`
- CIF and mmCIF coordinates: `.cif`, `.mmcif`
- MDL MOL small-molecule records: `.mol`
- MDL SD files: `.sdf`
- Tripos MOL2, PQR, PDBQT, GROMACS, and XYZ coordinates: `.mol2`, `.pqr`, `.pdbqt`, `.gro`, `.xyz`

The compact **Workbench** is organized as **Select · Analyze · Compare · Related data · Style · Animate · Export**. It supports one shared atom/property/boolean/spatial query language, named selections, independent ordered style layers, live labels and fixed-screen or selection-anchored annotations, exact result tables, distance/angle/dihedral overlays, contacts/clashes, valence- and geometry-screened hydrogen bonds with explicit-H/inferred-H/protonation-ambiguity confidence, correspondence-safe RMSD, geometry, SASA/buried area, density statistics, trajectory plots, multiple aligned objects, undo/redo, and complete named scenes. RMSD requires at least three non-collinear pairs, preserves explicit atom-pair order, matches unique biochemical identities independent of file order, requires matching alternate-location labels for otherwise unique candidates, and reports missing or ambiguous atoms instead of guessing repeated source-local model, symmetry, or alternate-conformer copies. Large pair analyses count every match, retain a bounded result set for fast pagination, and label exported result tables as complete or partial with exact row counts. Large SASA calculations use bounded spatial indexing, yield during neighbor planning and surface sampling, show live progress, and can be cancelled without publishing a partial result. Buried-area analysis requires two atom-disjoint partners and explains any overlap by count, coverage, and example atom IDs instead of reporting an invalid interface. The same revisioned state is visible to Codex immediately, including camera, maps, trajectory frame/playback, measurements, and provenance.

The primary representation control supports cartoon, surface, sphere, balls and sticks, and sticks for protein-like structures; small molecules use balls and sticks or sticks. The visible control, live Mol\* scene, and Codex context share the same representation state.

For model control, the compact `ballStick` and `stick` names correspond to canonical scene `ball_and_stick` (visible atom spheres plus bonds) and `lines` (thin lines) layers. The separate canonical `sticks` representation draws connected bond cylinders without atom spheres. Invalid aliases or structure/representation combinations are rejected without partially changing the viewer.

Load CCP4/MRC/MAP, DSN6, CUBE, DX, or DensityServer CIF maps from Compare, then change contour, mesh/surface/slice/direct-volume style, opacity, color, or selection zoning. Pair a PDB/mmCIF/GRO/XYZ/PSF/PRMTOP/TOP topology with XTC/DCD/TRR/NetCDF/LAMMPS coordinates to scrub, play, loop, align, stride, and analyze measurements across frames.

For a trusted workspace open, **Related data** can browse supported companions beside the source without exposing an absolute path. It stays inside the deepest active workspace root, ranks likely structures, maps, trajectories, and topologies, and requires confirmation before loading a suggested trajectory pair. Entries and files are bounded and rechecked immediately before the existing revisioned load path runs. Explicit local-file controls in Compare remain available.

The Export task can also **Save Project** and explicitly **Open Project**. Project Manifest v1 preserves the complete current scene, full named-scene bodies, maps, trajectories, annotations, measurements, storyboard, and analysis provenance while referring to molecular inputs only through relative labels, lengths, formats, and SHA-256 digests. Explicitly saved projects also preserve the Contents, sequence, measurement, command-bar, Workbench, and Render visibility preferences plus molecular picking mode; those preferences are restored only after the authenticated structure is safely loaded and ready. Older projects remain compatible, and presentation preferences never include command history, credentials, paths, or coordinates. The server offers source-associated project labels without absolute paths and verifies the primary source plus every dependency before the viewer changes. Missing, moved, changed, oversized, linked, escaped, or unsupported inputs produce a repair list and leave the current scene untouched. Successful saves use the same exact/versioned, no-overwrite artifact-and-provenance transaction as other exports.

## Render Images And Movies

Select **Render** for an image/movie panel using the canonical live camera, SelectionExpr layers, labels, and measurements. Images support PNG (default), JPEG, and host-supported WebP, with JPEG/WebP quality and optional automatic crop/padding. PNG and WebP may be transparent; JPEG is opaque. Unsupported encoders fail explicitly. The output retains exact source dimensions, crop rectangle, and final dimensions. Distance, angle, and dihedral overlays retain their Å or degree units in images and bounded H.264 MP4 movies. Live stereo views export monoscopically.

The editable storyboard provides guided recipes, camera spin/rock, molecular spin and actual assembly unwind, trajectory animation, renderer time, named-scene transitions, per-step duration/easing, object visibility, captions, validation/workload estimates, preview, progress, and cancellation. Trajectories can run once, loop, or use palindrome timing; quantization controls a bounded bitrate, not guaranteed constant-QP encoding.

Codex can also render fully specified scenes and ordered timelines itself. It can address the current selection, focus, or any named structure object; stage chains, ligands, contact residues, labels, measurements, fixed screen text, and molecularly anchored callouts; smoothly change residue colors and representations; move the camera or molecular objects along multi-step paths while callouts remain attached; align structures; fade molecules in or out; play coordinate trajectories; and set background, lighting, clipping, dimensions, duration, and frame rate. The completed artifact is returned directly from the mounted viewer.

Codex can inspect a saved or live render endpoint through `structure.get_state` without first loading that scene. The bounded endpoint retains the scene's camera, styles, exact targets, and opaque scientific-annotation references for image rendering or movie keyframes, without returning raw scientific arrays or measurement coordinates. An endpoint that exceeds 64 KiB or render limits is rejected, not truncated.

Density endpoints retain the admitted map-channel identity and its exact contour, color, opacity, style, visibility, and zone. Rendering verifies these sources without downloading maps; movie scene transitions switch map state at their midpoint. Provenance hashes the admitted source bytes, or the displayed bounded DX bytes for a native window—not an unacquired whole EMDB or native map. Unsupported or stale sources fail before rendering, and visible density is also identified in geometry-export provenance.

Alignment is also available outside movies. Codex can load multiple named structure objects, align selected chains or residue sets with structural, sequence-guided, or paired-atom methods, report RMSD and alignment scores, and independently transform, show, hide, list, or remove each object. A compact structure-object control appears only when multiple objects are present.

Each render is saved inside its bound publication root together with a `.render.json` sidecar containing the canonical replay specification, source provenance, renderer version, dimensions or timing, and SHA-256 hashes. Image and movie workloads are bounded before rendering.

The screenshot panel can download or copy its owned image when the host permits that gesture. These are delivery controls, not separate scientific capabilities: Codex can generate the same format and crop and return the authorized artifact or workspace destination, but cannot invent clipboard permission or simulate user consent. Source/unit validation and native encoder/browser verification remain separate checks.

## Data Handling

The plugin runs a local MCP server. Native workspace opens use Codex host-managed resource handles. Chat opens expose an opaque local plugin resource through standard MCP `resources/read`. The allowlisted `gfp-1ema` example resolves only to the packaged `examples/1EMA.pdb` and is verified against its pinned byte length, atom count, and SHA-256 digest before opening; arbitrary package-relative paths are not accepted.

Known text structures request host `text` representation explicitly, while known binary maps and trajectories request `blob`; auto-detection is reserved for unknown dependency formats. Native host ETag and writable metadata is parsed as typed capability information and kept private from chat/project resource identity, model context, projects, and artifacts. Missing, read-only, unsupported, malformed, ambiguous, or mixed-URI metadata cannot grant write authority. Opened sources remain immutable: this version neither subscribes to nor replaces them, and `writable: true` does not alter the create-new derived-artifact workflow.

File contents are sent to the embedded viewer, not returned to the model as tool output merely to open the file. Inputs, queries, analyses, trajectory sampling, renders, command queues, serialized context, and artifact staging all have explicit hard budgets. Text is bounded by UTF-8 bytes, binary resources are decoded in bounded chunks into typed buffers, and topology-plus-trajectory pairs share one input budget. When the MCP host supplies active workspace roots, chat opens are confined to those roots. MP4s and large structured exports cross the MCP proxy in bounded, resumable chunks; byte length, format, provenance, and final SHA-256 are checked before the artifact and sidecar are published atomically. MP4 total size is separately quota-admitted from destination free space and configured disk policy while each raw chunk remains at most 192 KiB. WebCodecs fragmented-MP4 output streams with backpressure during encoding, and authorized saves use a private destination-adjacent staging inode so publication needs no second file-sized copy. Unfinished staging expires after inactivity or transport shutdown. Small structured exports use a proxy-safe idempotent fast path. With an active root, derived images, MP4, scene, coordinate, model-archive, geometry, and CSV artifacts share a bounded destination browser inside the deepest containing root. When root discovery is unsupported or empty, an exact chat-opened source may instead retain publication-only authority for its captured writable project root; open no-follow handles and pinned source/root identities are revalidated for every use. That fallback does not enable related-data or project-manifest reads and fails closed if later active roots are unrelated. The browser starts beside the opened source, displays only relative labels, traverses only the bound publication root, and can create one safe child folder. Direct relative-path entry remains available. Exact collisions stop without changes; versioned saves choose `stem.ext`, `stem-2.ext`, and later names while atomically reserving the artifact and provenance pair without overwrite. The server—not the widget—binds opaque navigation and reservation tokens to the session, source/root/directory identities, caller, command, format/extension, and expiry, rejects path and identity races, and returns relative metadata only; the capability fails closed without active-root or captured publication authority. Rendered media and explicit structured exports are written only when requested and are confined to the bound publication root. Result CSVs use UTF-8, CRLF records, and quoting for every field so quoted-CSV importers keep embedded spreadsheet separators inside the source field; fields that could be interpreted as formulas use a documented, reversible leading-TAB safety marker. The export response and provenance sidecar expose the exact `spreadsheetSafety` contract. The viewer does not use the host-resource conditional replacement API from #990981 for these derived exports: they create new artifacts and require resumable transfer rather than replacing the opened source file.

Historical chat viewers can restore unchanged files after Codex restarts. The plugin keeps only bounded, owner-private path/file-identity metadata and successfully served presentation capabilities for up to 30 days; it does not persist structure contents in these registries, and unserved presentation handles remain invalid. If a file moved, changed, expired, or is no longer inside its applicable active root or still-current captured project/source authority, the card explains the condition and offers a return-to-chat handoff so you can reopen the current file explicitly.

Authorized chat scenes also save bounded checkpoints in a separate owner-private store during normal editing. This includes exact chat-opened files with publication-only authority: automatic recovery does not grant workspace browsing or explicit project-file access. The latest successfully saved scene can be restored after task navigation or a Codex restart, provided its presentation, source, and admitted dependencies still validate. Synchronization with the molecular canvas alone does not confirm durable storage. A failed save keeps the edit visible, reports the failure separately, and offers **Retry saving** when possible.

A replacement viewer must restore the saved scene before accepting commands. Old frames cannot complete commands, save checkpoints, or publish artifacts after ownership transfers, including across MCP restarts. If recovery fails, the saved checkpoint is retained and the viewer reports the failure instead of treating a default scene as recovered. Checkpoints are not permanent project archives: use **Save Project** for an explicit portable project.

Live command sessions tolerate sleep and expire after 24 hours without renderer activity. After longer disconnection, chat viewers reconnect only if the saved presentation, source, and renderer ownership still validate. Native fallback viewers offer **Retry viewer controls**, which obtains a fresh session reference while preserving the visible structure; native context can reconnect through **Ask about selection**. Saved presentation and checkpoint retention are separate from this live connection limit.

## Marketplace Package

This package is a generated, self-contained runtime bundle for the Codex official plugin marketplace. It includes the manifest, local MCP server runtime, viewer assets, agent guidance, the pinned GFP example, and small synthetic smoke fixtures needed to validate supported formats.

## License

OpenAI-authored files are available under the [MIT License](LICENSE). The bundled RCSB PDB 1EMA data file is available under the [CC0 1.0 Universal Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/) and retains its source, DOI, revision, and digest in `examples/starter-examples.json`. Bundled third-party dependencies and their available license or notice texts are listed in `THIRD_PARTY_NOTICES.md`, which is included in the generated marketplace bundle.

SHA-256: 7620095d02ef6890737b63fe4f28bddab16a8ebf646f965184ef2cde34d0e583