Accept: text/markdown.Use TomoJAX from an AI agent
Let an AI agent drive TomoJAX through the Model Context Protocol.
tomojax mcp runs a Model Context Protocol server over stdio. An agent connected to it can inspect, load, correct, align, reconstruct, simulate and export scans, look at the results as images, and run Python against the data it has loaded. No tool waits for a person, so an agent can work through a scan unattended.

What the agent sees after reconstruct on the FIPS walnut (three orbits, FISTA): the central planes, labeled with the result's handle, the plane, its extent and the display limits, beside a short text summary.
Install and connect
Install TomoJAX and the matching tomojax-studio wheel in the environment your MCP client will start. The wheel includes the native worker. For local CUDA 12 and physical X-ray spectra, run:
uv pip install --prerelease=allow "tomojax[cuda12,spectra]" tomojax-studioFor a remote connection, install TomoJAX with the compute machine's CPU or CUDA dependencies there. On the laptop, tomojax mcp --connection NAME starts the native server for that connection. With the base package alone, tomojax serve runs the Python executor. If the launcher cannot find tomojax-worker in its environment or on PATH, tomojax mcp prints the install command for the matching Studio wheel. See remote session setup.
Claude Code
Add the server, then allow its tools so that calls run without a permission prompt:
claude mcp add tomojax -- tomojax mcp{
"permissions": {
"allow": ["mcp__tomojax"]
}
}Put the permissions block in .claude/settings.json (shared with the project) or .claude/settings.local.json (yours only). To share the server with a project instead, commit a .mcp.json:
{
"mcpServers": {
"tomojax": {
"command": "tomojax",
"args": ["mcp"]
}
}
}A project server needs approval once per checkout. Pre-approve it with "enabledMcpjsonServers": ["tomojax"] in .claude/settings.local.json.
From a development checkout, build the worker with (cd studio && cargo build --locked -p tomojax-worker). Put the directory containing that binary on PATH, then run uv run tomojax mcp.
The repository also carries a Claude Code plugin in plugins/tomojax/, with this server and the Agent Skill described below.
Codex and other clients
Any MCP client that starts stdio servers can run the same command. For Codex, add to ~/.codex/config.toml:
[mcp_servers.tomojax]
command = "tomojax"
args = ["mcp"]Inspect and submit jobs on another machine
A stdio client on your laptop can use a named connection from ~/.config/tomojax/connections.toml. This Codex entry starts the server for a connection named beamline.
[mcp_servers.tomojax_beamline]
command = "tomojax"
args = ["mcp", "--connection", "beamline"]Use status to see the connected host, working directory and job launcher. Data paths belong to that machine. If the connection needs a login, run tomojax-worker connect beamline --login in your terminal, then retry the call. While the executor starts or waits for an allocation, scientific tools return unavailable. Poll status until the executor is ready, then retry the call. You can still list jobs, inspect directories and transfer files. Use open for a session handle, then pass that handle to a correction or reconstruction. view can show planes, projections, sinograms and differences, report statistics and line profiles, and plot or tabulate poses. Use preview to compare corrections or sweep the rotation center. Use marks for points, labels, arrows, boxes, circles and paths. A mark can use array indices or a pixel from one of the last 256 view images. Point marks can snap to a peak, trough or edge. Use a registered feature for an outline that follows the grid across views. The python tool runs in the executor on the connected machine, so its files and devices are that machine's.
To run a small simulation, pass these arguments to submit.
{"operation":{"type":"simulate","size":16,"n_views":24}}Keep the returned job ID. With the process or Slurm launcher, you can close the client and reconnect later. Call jobs with no arguments to list jobs, or with {"job":"ID"} to read one job's progress, receipt and result slices. Pass the returned byte offset on your next poll to read subsequent records. To request cancellation, pass the job ID to cancel_job.
submit also accepts correct, reconstruct, reconstruct_slabs and align. Give a detached operation the paths of its saved inputs. The connection's results directory holds the jobs, with ~/tomojax as the default. To work with a different results directory, pass the same results argument to submit, jobs and cancel_job.
To bring a slice image to the laptop, call download with {"path":"slices/center.png","to":"center.png"}. To send a file to the worker, call upload with {"from":"mask.npy","path":"inputs/mask.npy"}. The laptop paths (to and from) resolve against CLAUDE_PROJECT_DIR or the server's working directory. Both tools copy one file up to 100 MiB, verify its SHA-256 digest and require a new destination in an existing directory. Uploaded files inherit the target umask and directory ACLs.
Install the Agent Skill
The TomoJAX Agent Skill teaches an agent how to use TomoJAX well: when to use the server and when its own Python, how to choose a method and check a result without ground truth, how to agree a feature with you by marking it, and how to report a bug. It follows the Agent Skills format and ships inside the tomojax package. Copy it into the directory your agent reads skills from:
tomojax skill -o ~/.claude/skills # Claude Code, every project
tomojax skill -o ~/.codex/skills # Codextomojax skill with no options prints where the Skill is and the usual locations. Pass --force to replace an earlier copy after upgrading TomoJAX.
Tools
| Tool | What it does |
|---|---|
status | Versions, devices, GPU memory, live handles and running jobs |
inspect | Report on a file and what loading it reads, list the datasets and checkpoints in a directory, show an HDF5 tree, or describe a checkpoint |
open | Load a scan, raw frames, or a saved result as a handle, with metadata overrides, dataset path selectors, and explicit flat/dark calibration (apply_poses applies only to scans and frames) |
describe | Expert settings for an operation or solver, with defaults and units |
correct | Flat/dark correction (default flat_weights="views", or "position"), zingers, phase retrieval, rings, beam hardening and binning |
reconstruct | Reconstruct with an automatic or named method; returns central planes |
reconstruct_slabs | Reconstruct raw frames slab by slab into a NeXus file; saves and returns whole-scan truncation and iterative stopping diagnostics |
align | Fit the rotation center, setup angles or per-view motion; returns slices, a pose plot when per-view motion is fitted, and disturbed_views screening for joint fits |
simulate | Simulate a scan of a phantom, with optional detector artifacts |
project, backproject | Apply the forward projector or its exact transpose |
edit_scan | Select views, crop, bin, replace poses or combine scans |
preview | Single slices, center sweeps (with optional roi zoom), before/after corrections and region estimates |
view | Planes, projections, sinograms, differences, profiles, statistics, pose tables and pose plots, with marks and feature outlines |
feature | Make a named mask from a box, sphere, cylinder or prism, a region grown from seed points, or a band around another feature |
evaluate | Score candidate settings on held-out views |
save, export | Write a dataset or feature mask with its embedded processing record and return the written paths, or export a registered volume. Use dry_run to inspect destinations, axes, value mapping and space requirements |
control | Cancel, pause or resume a session request, close a handle or restart the worker |
python | Run Python on the connected machine with live handles and tj in scope |
submit, jobs, cancel_job | Start, inspect or cancel a durable job on the connected machine |
download, upload | Transfer a file between the laptop and the connected machine |
Tools that accept dry_run report what a call would do without running it: the method and grid a reconstruction would use and its memory estimate, the files an export would create, or the shapes a simulation would produce. Use describe before setting expert keys in config. A call with a malformed argument returns an error that shows the shape the argument should have, so the agent can correct it on the next try.
Handles and references
Each result is kept in the server as a handle with an ID such as @scan-3fa94c1e. Pass that ID to any tool that takes data. Add a member to choose part of a result, for example @align-91c0d2aa.scan for the aligned scan or @sim-07be55f1.phantom for a simulation's phantom. A bare handle gives the whole object to save and export, and its main array (volume, projections, phantom or working image) to an array field.
Workflow source fields accept acquisition paths through the normal loader. For array fields, use a handle member, a session array such as @array-…, a .npy file or an explicit HDF5 dataset such as scan.h5::/entry/data/data. Literal arrays use storage order. Relative data paths resolve against the connected worker's directory, shown by status. Write ./@name for a file whose name starts with @.
To view or backproject measured line integrals, use open and select the scan's .projections. For raw counts, open with kind=frames and select .counts. Use inspect with preview=true for a first look, or preview with correction_preview to compare raw and corrected rows.
view and the volume field of project also accept saved TomoJAX volumes by path (.nxs or .h5). They use logical (z, y, x) order. The worker's read and statistics commands use the same references as view and can read a region of a saved volume or lazy frames handle in bounded tiles.
Handles last until you close them, the worker restarts, or the server exits. Save results you want to keep. An ID from an earlier session returns an error that lists the live handles.
Results, images and long jobs
Every result has a short text summary, the same fields as structured content, and labeled PNG panels where an image helps: three central planes after reconstruct, working slices (and a pose plot when per-view motion is fitted) after joint align, and the requested planes from view and preview. Panels that are meant to be compared, such as a center sweep, share one display range. Large results are cut to fit the client's limits, and the rest is served as tomojax://result/... resources that the result names. Each connection retains up to 64 MiB of paged replies for up to 15 minutes, evicting the oldest first. Repeat the call if a page has expired or been evicted.
Long jobs send progress with the current stage, its metrics and an estimate of the time left. Clients that support the MCP tasks extension receive long calls as tasks they can poll and cancel; other clients wait for the result and can cancel a running job by reading its ID from status and calling control with action="cancel". A canceled job stops at the next work boundary (an iteration, slab, or alignment step), saving first when it has a checkpoint.
The server runs one worker connection with one execution queue, so GPU jobs run one after another. While connected, the MCP server sends periodic heartbeats every 15 seconds so calls longer than two minutes keep their worker alive past its idle timeout. Running out of GPU memory returns an ordinary error with suggestions, and the existing handles stay. If a reconstruction fails with The CUDA context is lost. Restart the process., call control with action="restart" to start a fresh worker (existing handles are discarded). If the worker process itself dies, the server reports which handles were lost and starts a new worker.
What the loader and solver report
inspect on a file includes a loading section describing what open reads without extra arguments: full_turn for closed axial parallel orbits (plus axis_to_edge_px, field_of_view_px, overlap_px, and central_gap_px when the axis is known and roll is a multiple of 90°), length_unit ("pixel" when no pixel size is recorded), center ("not_recorded" when the rotation center defaults to the detector middle until fitted), geometry ("not_recorded" when no rotation axis or pixel scale is recorded), frame_records (the counts of frames, image_key, and angles when a scan stopped early and loading trims to their common prefix), or message naming a missing argument. The text summary repeats these fields, and every scan, frames, reconstruction, and alignment result carries detector_center_status, geometry_status, and frame_records in its geometry field. When loading.geometry is "not_recorded", reconstruction and alignment refuse the scan until you open it with geometry, such as {"kind": "parallel"} (or "lamino" with tilt, or "cone" with source_to_axis and source_to_detector).
Iterative reconstruct results carry every scalar diagnostic the solver reports alongside the stopping summary in the text (for example, "78 updates, stopped at the estimated noise level; automatic TV weight 4.75e-05" or "7 updates, stopped at the estimated projection discrepancy"). Read termination ("projection_discrepancy" for CGLS/SIRT, "noise_score" or "objective_tolerance" for FISTA, "converged", "roundoff_limit", "numerical_breakdown", or "iteration_limit"), early_stop, and effective_iterations, plus resolved_tv_weight and noise_score_rms for FISTA and measurement_noise_rms and projection_error_rms for CGLS/SIRT. Every reconstruct result also carries truncation (edge_ratio, outside_fraction, interior_shift, radius, and field_of_view_radius); iterative results add outside_grid, data_model ("continued_exterior" or "measured"), and background_treatment ("subtracted", "additive_poisson", or "none"). When outside_fraction rounds to at least 1% (0.5% or above), the text summary appends "N% of attenuation beyond the detector"; when an iterative exterior fit ran, it also appends "modeled exterior subtracted from fit data" (CGLS, SIRT, FISTA, SPDHG) or "modeled exterior added to the Poisson mean" (MLEM). To turn off exterior modeling, pass config: {"exterior": "zero"} with an explicit method to reconstruct or reconstruct_slabs. The saved configuration records the choice.
reconstruct_slabs writes the NeXus volume directly, saves the whole-scan record (truncation, config, host_slabs, source, resolved backend for Fourier, and iterative stopping diagnostics including slab_stopping on independent planes) in the file's reconstruction_info (returned by inspect under volume.reconstruction_info), and returns those same fields in its structured summary alongside paths; its text summary includes the stopping line and "N% of attenuation beyond the detector" from 1% up (plus the iterative background treatment when an exterior fit ran). align results carry calibration and diagnostics (focus_px, binning, views, and pairs for half-turn focus, or estimator, pairs, rows, and overlap_px for full-turn opposing-ray center fits). Joint align results also return disturbed_views (score, flagged half-open ranges, angles, and a review message appended to the text summary) and fit_views when views are excluded. Pass exclude_views, detector_columns ("fixed", "transient", or "both"), or image_tv_weight: "coverage" in config (use describe on align for all keys).
correct, reconstruct_slabs, and preview (correction_preview) blend bracketing flat sets with flat_weights="views" by default; pass flat_weights="position" to blend by position alone. When the views move the flat by more than 1% over more than 1% of the detector, the tool returns a warning in notes (and in the text summary) noting that the views do not follow the flat sets' positions and that a shadow covering both flat sets with no open-beam views leaves the incident intensity uncertain. To use clean flats from a matching scan, pass that scan's path as flats on open.
Every handle reply that carries a scan (open, correct, reconstruct, align, simulate, and edit_scan) returns the ordered correction records from scan.corrections in structuredContent.corrections. The flat_dark record includes its settings and findings such as flat_weights_from_views, later_flat_weight, flat_structure_unmatched, and flat_moved_by_views. A large numeric list appears as null in the record, with its array reference under the matching JSON pointer in info.arrays (attached to structuredContent.info even at detail="summary"). save returns the saved dataset path in structuredContent.paths and as a resource link.
Long jobs that must survive a kill
Use submit on a process or slurm connection for work that must keep running after the client disconnects. For reconstruct, reconstruct_slabs and align, the launcher assigns a checkpoint directory inside the job folder by default. Reconnect and read the job with job. If the scheduler preempted it, the job reports which checkpoint can be resumed.
For an inline solve, pass checkpoint to one of those three tools, or checkpoint=... to the corresponding TomoJAX function inside python. Relative paths are resolved in the worker's directory. On local and named connections, closing MCP input or sending the server SIGTERM gives a checkpointed solve up to 120 seconds to reach an iteration, slab or alignment boundary and finish saving. If a scheduler signals only the MCP client, the client must stop its server in time for the save. Canceling a typed call with control or MCP task cancellation while connected returns a canceled error with the directory in checkpoint and instructions in next.
To resume, repeat the call on the same machine with the same input, arguments and checkpoint directory. If the worker loses the connection, the deadline expires, or the node suffers a hard kill, only previously committed state is available. A slab reconstruction keeps finished slabs in checkpoint/volume.npy. TomoJAX removes the directory when the solve completes. Checkpoint contents and save intervals
Handles do not outlive the server, so a later session cannot reuse @scan-… IDs. Before a long run, save the input scan and run from its path; the call can then be repeated exactly. To pick up another session's work, inspect the working directory, which lists checkpoints, then inspect a checkpoint: it reports the run's operation, method and settings, the request that started it (its worker operation with tagged source objects such as {"type": "path", "path": "..."} and the provenance of its inputs; pass source as the path string when calling the MCP tool), when it was last saved, and whether a running process still holds it (in_use).
Point at a feature
An agent can show you exactly what it means instead of describing it. view takes marks: points, arrows, boxes, circles, polylines, polygons and text, each with an optional label and color. A position is either array indices of the source, [z, y, x] for a volume or [view, v, u] for projections, or a pixel in an image an earlier view returned, {"pixel": [x, y], "image": "render-12"} with the origin at the top left, which the server converts to indices. Either way a mark lands on the same voxel in every plane, ROI and zoom; a circle is a sphere, and each plane shows its cross-section. Index ticks along the image edges, or a pixel grid with grid, help the agent aim. The result reports, for each mark, its positions in array indices and, for each plane, whether it was drawn, its pixel in the image, the value under it, and that value's percentile in the plane and place within the display limits. A point or arrow head on flat ground, with no peak, trough or edge within 2 samples, also gets a warning and nearest: the array indices, distance, value and percentile of the closest structure on that plane, so a miss names where the feature is. A point with snap set to peak, trough or edge moves, on each plane, to the brightest or darkest sample or the steepest edge within within index units (5 by default), and the report gives where it moved to and how far.
view images stay within 1568 pixels on the long edge and 1.15 megapixels, so a model sees them unscaled and its pixel positions match the server's. Give source a list to show several candidates side by side on the same planes, with the same marks and outlines, and limits to fix the display range.
Once you agree on a structure, the feature tool turns it into a named mask held by the server: a box, sphere, cylinder or extruded polygon from the mark, a region grown from a seed point through voxels of similar value, or a band of chosen width around another feature. view with features outlines up to five features on any volume on the same grid, which is how an agent shows what it will optimize for, and the Skill's feature_scores.py scores candidate reconstructions on a feature and its surroundings without ground truth.
Bands, feature outlines and side-by-side views require the same physical sampling at every array index. The tools compare shape, axis order, frames, axis units, fixed planes, origins, signed pitches and complete coordinate vectors. The absolute tolerance is 1e-6 in each axis's unit. Use a feature made on the target grid or resample the mask explicitly before measuring it. Volume differences also require matching value units. The MCP view difference can transpose a saved volume by its axis names to compare the same voxels.
For an inner rim one voxel thick, use inner=-1, outer=0. The space beyond every grid face is background, so the rim follows the feature even where it meets a face, edge or corner of the volume. An outer band includes only source voxels. A full-volume feature thus has an empty outer band, with count zero and null moments.
Files
A saved feature stores a compressed mask under /entry/masks/<name>/data.
Its record holds the recipe, bounding box, coordinate axes and lineage. Reopen
it with kind="feature" to view, export or use the mask again.
save, export and reconstruct_slabs refuse to replace an existing file unless the call sets force. Files stay protected while a running operation, open handle, unreleased artifact or reachable Python result depends on them. A dry run releases its inputs on success or failure. Protection covers HDF5 links, virtual datasets, external raw storage, individual frame files and calibration from another scan. It also applies to sidecars and checkpoint directories. A conflicting path, including a symlink or hard link, returns an error naming the input. Choose a different destination. Each output is written beside its destination and moved into place once whole.
The tool annotations identify read-only operations, including jobs, and operations that can discard work or replace files, including cancel_job, save, export, reconstruct_slabs, control and python.
Python
python runs code in the worker, beside the loaded data, with tj, np and handles in scope. handles maps live IDs to their TomoJAX objects, and ID.member selects a member as in the typed tools. register(obj) publishes a new handle from a Scan, Reconstruction, array or other result, and register_feature(mask, like=ID) a feature on that object's grid. view(...) renders planes with the same arguments as the view tool, marks and features included, and show(array, marks=...) adds an image of a 2D array to the reply. Variables persist between calls until reset or a worker restart.
Use it for compound work and for anything the typed tools do not cover: a sweep of reconstruction settings in one call, a custom geometry, a direct solver such as tomojax.recon.cgls, tomojax.forward, phase unwrapping or your own analysis. The result is the last expression, with arrays of more than 16 values summarized by shape, dtype and range. Errors report the exception and the lines of your code it passed through; set traceback for the full trace. Long calls run as tasks and can be canceled at TomoJAX's work boundaries (an iteration, slab, or alignment step). The tomojax://guide/python resource has worked examples.
Guides and prompts
The server publishes the Agent Skill's references as resources, and its workflow guides also as prompts, which Claude Code lists as slash commands: reconstruct-scan, lab-ct-start-to-finish, find-the-center and check-a-reconstruction. Read them as tomojax://guide/{topic}, alongside python, solvers, geometry, calibration, pointing-and-features, tuning-without-truth, thin-shell, large-scans and reporting-bugs. tomojax://handle/{id} gives a handle's summary and provenance, and tomojax://describe/{operation} its settings.
Transport and session lifetime
The server communicates over stdio on the agent's machine. The connection selects the worker that owns the scan and compute devices. Live handles and active tasks persist for the lifetime of the server process; use save or export for results you want to keep across sessions.
To export an aligned scan as sinograms, give export the scan's <handle>.projections member, a destination path and axis="v". Use dry_run=true to inspect the written axes, shape and file list.