Skip to content

EMhub-Tomo MCP server (emhub-tomo-mcp) and small API additions - #158

Closed
sergiocruzleon wants to merge 28 commits into
develfrom
dev-sc_mcp_server
Closed

sergiocruzleon wants to merge 28 commits into
develfrom
dev-sc_mcp_server

Conversation

@sergiocruzleon

Copy link
Copy Markdown
Collaborator

@delarosatrevin , here is the MCP server for EMhub-Tomo, ready for a first look. This is a draft; please don't merge yet.

What it adds

emhub-tomo-mcp/: a self-contained MCP server (Python ≥ 3.10, uses EMhub only through its REST API). It has read tools (projects, jobs, logs, files, STAR tables, previews). Write tools (create projects, load workflows, edit, run, schedule and stop jobs) are opt-in, with checks on parameters, queues, GPUs and launch rates, and an audit log.
emhub/blueprints/api.py, additive only:
get_workflows: yours from jm_mcp, extended with each template's jobs;
get_job_types;
validate_job: checks parameters without saving;
load_workflow also returns the new job ids;
get_file_preview takes optional slice='center' and max_size.
These are the parts of the diff that touch EMhub itself.
Tutorial: the Warp ApoF tutorial, run end to end through Claude Code with this server, with the real conversations and screenshots: emhub-tomo-mcp/docs/apof-tutorial.md . Part 2's results will be added when the run finishes.

Testing

Unit and protocol tests: 310.
Contract tests: 19, against a throw-away EMhub with stub programs.
Agentic evals with read and write access.
A live run on MPCDF phys (here at MPI).
CI runs on this branch.

validate_job calls emwrap's private _readJobParams and _validateJobInputs. A public method in emwrap would be cleaner.
The tutorial run found that part 2 of the ApoF workflow points at WarpMCreatePopulation/job022, which doesn't exist once part 1 is loaded into a project. I have notes on this and about 20 other emwrap/emhub issues, and will file them separately.

delarosatrevin and others added 27 commits October 23, 2026 18:15
List the processing workflow templates (ProcessingConfig.get_workflows)
over the REST API, so clients can choose one to load with load_workflow.

Taken from commit 976dfe2 on the jm_mcp branch. Only this endpoint is
included; the tilt-series viewer changes from that commit are not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
emhub-tomo-mcp/tests/support/emhub_instance.py starts a minimal EMhub
instance on a free localhost port inside an existing EMhub-Tomo
installation (random admin password, no debug mode, no auto-login) and
removes it afterwards. It is the base for the MCP server's contract tests.

emhub-tomo-mcp/scripts/record_api_samples.py uses it to record real
request/response pairs for the endpoints the MCP server will use, into
emhub-tomo-mcp/tests/fixtures/api/ (paths and passwords masked).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
emhub-tomo-mcp/tests/support/emhub_instance.py is split into reusable
pieces (create_instance, start_server, wait_until_serving, stop_server),
with paths made absolute (Flask rejects a relative instance path).

scripts/dev_server.py starts, reports on and stops a long-lived
development server built from the same pieces (127.0.0.1 only, random
admin password, no debug mode, no auto-login).

scripts/run_tutorial_via_emhub.py runs the ApoF tutorial through a
running server's REST API, with jobs submitted through a cluster queue,
and follows them until they finish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Explains what the folder contains so far (the development and test
tooling for the MCP server) and how to run the scripts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
List the job types registered in emwrap's ProcessingConfig (id, label,
output folder type, menu visibility, whether a form exists). The processing
menu config is not a reliable registry: it can list types that do not
exist and omit ones that do (e.g. the RELION tomo jobs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A self-contained package (Python >= 3.10, mcp >= 2.3 < 3) that gives MCP
clients read-only access to EMhub-Tomo processing projects through the
EMhub REST API. It imports nothing from emhub, emwrap or emtools.

- Tools: get_server_status, list_projects, get_project, get_job,
  get_job_logs, wait_for_jobs, list_job_types, describe_job_type,
  list_workflow_templates, list_project_files, read_project_file; guide,
  job-graph and form resources; diagnose_job and project_report prompts.
- Layers: emhub/ (async REST client: auto-login or password with
  re-login, read retries, error mapping), domain/ (visibility following
  EMhub's processing page, job graph and logs, job types and forms,
  files, project-relative path checks, pagination and windows), server/.
- get_job and get_job_logs warn when a job marked finished shows signs of
  failure (a traceback, error lines or missing outputs): emwrap can mark
  such jobs finished.
- Errors carry a category and a reference id; details stay in the log.
- CLI: stdio server, --check, --print-config; logs on stderr only.
- Tests: unit and protocol tests against a fake EMhub built from recorded
  responses, stdio tests, and contract tests against a real throw-away
  EMhub-Tomo with stub launchers (190 tests, 97 % coverage).
- Docs: README, configuration, client set-up, security model, development
  guide, generated tool reference.

The test helper now reaps the server it started instead of polling its
process group, and the scripts were reformatted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Testing against real data, odd EMhub answers and a real auto-login server
found these problems, now fixed:

- A project whose folder was deleted made describe_job_type and the form
  resource fail for everyone (forms are read in some project's context).
  Forms now use the first project whose folder exists, and a missing
  folder is reported as not_found with the folder path.
- A text file EMhub cannot decode (not UTF-8) came back as empty text.
  The read error is now reported in the note.
- One malformed record (e.g. a user with roles null) made every tool
  fail. Lists and job graphs are parsed item by item; malformed items are
  skipped and logged, and null lists or dicts are read as empty.
- describe_job_type returned zero parameters for job types without a
  form; it now says that there is no form.
- get_project on a 1000-job project exceeded the response budget: jobs
  are listed 100 at a time by default, the failed, active and ready
  lists are capped at 50, and the summary names at most 5 failed jobs.

New tests: random-argument fuzzing of every tool, a 1000-job project,
50 concurrent calls with one login, EMhub down then up, session loss,
malformed data, a memory check over 900 calls, and contract tests for
auto-login (as served by emh-tomo --run), deleted project folders and
non-UTF-8 files. scripts/sweep_real_data.py exercises every tool against
the projects of a real EMhub server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- tests/evals/run_evals.py runs scenarios with Claude Code (headless, only
  this server's tools) and grades the answers with deterministic checks
  (patterns that must or must not appear, a tool-call budget); --regrade
  re-applies changed checks to saved answers without new runs.
- tests/evals/apof_scenarios.json: 11 scenarios on the ApoF tutorial
  projects (facts, diagnosis, a misleading project title, a refused change
  request, a prompt injection in a project file, a path-traversal request,
  an unknown project, warnings in finished jobs). All pass; one run of all
  11 cost about $3.
- Cursors are checked against the URL-safe base64 alphabet before decoding
  (Python 3.11 warned about lax decoding of fuzzed input).
- run_tutorial_via_emhub.py: --tilt-series imports a single tilt series,
  for short live tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- /api/validate_job checks job parameters against the job type's form
  (for an existing job, merged with its current parameters) without
  saving or running anything; with for_schedule, inputs produced by
  parent jobs may not exist yet.
- /api/load_workflow also returns 'job_ids', the map from the template's
  job ids to the new jobs, so clients know which jobs were created.
- /api/get_workflows also lists each template's jobs (id and type).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With EMHUB_TOMO_MCP_ACCESS=operate the server also has tools that change
projects: create_project, load_workflow_template, save_job, run_job,
schedule_jobs, stop_jobs, annotate_job, tag_jobs, duplicate_jobs and
export_workflow; 'admin' adds delete_jobs and clean re-runs.

Every change is checked before it is sent: the access level on the
project (owner, editor, viewer); the job's status (running jobs are not
edited, re-run or deleted; finished jobs are re-run only on request);
parameters against the job type's form, then with EMhub's validation;
queue parameters; GPU jobs only on cluster queues, with a default queue;
limits on GPUs per job, GPU jobs at once and launches per hour; projects
only inside allowed folders. Changes support dry_run, are serialized per
project, are never retried when unconfirmed, and are written to an audit
log.

get_project now lists scheduled jobs that will never start because a job
they wait for failed or was aborted, and wait_for_jobs stops waiting for
them (emwrap keeps them scheduled indefinitely).

Tests: operations against a stateful fake EMhub, protocol tests per access
level, contract tests that drive a pipeline through MCP on a real EMhub
with stub launchers, and an opt-in live test on a cluster queue. The
contract helper now also stops the instance's detached schedule watchers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
get_jobs returns up to 20 jobs in one call, so comparisons need one
round trip instead of many. get_star_table reads STAR files (tables,
selected columns, pages of rows, counts per value), so questions such
as "how many particles per tomogram" need no file windows.

Hardening tests: concurrent launches on one project are serialized;
a slow EMhub over real HTTP times out within the configured limits and
changes are not retried; get_project on a 200-job project stays within
a latency budget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
EMhub describes an output as '<type> (<info>)', and emwrap's info for a
file that is not there is 'Missing: <path>' ('Pending' while the job is
active). Only 'File (Missing' was recognised, so typed outputs such as
RELION optimisation sets were reported as existing, and get_job did not
warn about finished jobs with missing outputs. 'No-info' and 'Error'
describe files that exist; an empty description is now 'unknown'.

Found by the read evals; checked against the files on disk for all 127
described outputs of the tutorial projects (no mismatch).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cs, CI

- tests/evals/run_write_evals.py: agentic evals with write access on a
  throw-away EMhub whose programs are stubs. Each scenario gets its own
  project; the model acts with 'operate' access and no default queue.
  Graded on the answer and on the resulting state (audit log, statuses,
  parameters, labels). 8 scenarios, 24/24 runs pass (3 each).
- docs/deployment.md and docs/troubleshooting.md; the error table in
  configuration.md gains 'conflict'; development.md describes the
  hardening tests, the live test and both eval suites.
- Tests: the docs' relative links and anchors resolve; the version
  matches pyproject.toml, the installed metadata and the changelog.
- .github/workflows/emhub-tomo-mcp.yml: lint, types, unit and protocol
  tests on Python 3.10-3.13, package build. Not yet run on GitHub (the
  branch is not pushed); the same steps pass locally on 3.10 and 3.13.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Release of the MCP server for EMhub-Tomo (Phases 1-3 of the plan).
Version 1.0.0, production/stable classifier, the changelog entry, the
README status, and a copy of the repository's GPL-3.0 license so that
built packages carry it.

Gates passed for this commit: ruff, mypy (strict), 299 unit and
protocol tests (Python 3.10, 3.12, 3.13), 19 contract tests against a
throw-away EMhub with stub launchers, write-access evals 24/24.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
emwrap devel (33a1d72, "Added validation for failed TS in Warp jobs")
now fails a Warp job that produced no tilt series, and finishes it with
a "WARNING: N of M ... failed" line when only some failed. Before, such
jobs always finished.

- Contract tests: the motion correction whose program is a stub now
  ends 'failed'; its error ("No output ... tilt-series were produced")
  is checked instead of the warnings of a finished job. In the scheduled
  pipeline, the jobs after it are reported as blocked and cancelled.
- Unit test: a finished Warp job with the new partial-failure line gets
  a warning naming the failed tilt series (stubs cannot produce this).
- The fake EMhub takes per-job stdout, like stderr.

No change to the server was needed. 19/19 contract tests pass against
emhub, emwrap and emtools devel of 2026-10-23.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The ApoF template on emwrap devel numbers its jobs differently (the
import is now EMwrap/job001, it was job002), so the ambiguity scenario
checks for any template import id plus the copy (job012). Regrades:
8/8 on devel, and the earlier 24 runs still pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The answer "There's no EMhub-Tomo project 42 ... [not_found]" was graded
as a failure. Regraded: 11/11 on the dev server running emhub devel, and
the Phase 1 results still pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ainst

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Found while running the ApoF tutorial through MCP: the GPU rules only
recognised job types whose form has 'gpus'. RELION forms give GPUs as
'gpu_ids' (emwrap ignores their 'gpus'), so a RELION job without a queue
would have been allowed to run on the EMhub host, and its GPU count was
not checked against the limits.

- A job type can use GPUs if its form has 'gpus' or 'gpu_ids'.
- A job's GPUs are counted as emwrap counts them for a cluster
  submission (ProjectManager._count_job_gpus): distinct ids of 'gpu_ids'
  if set, else of 'gpus' ("0 0 1" is 2 GPUs, not 3). Empty, zero or
  unreadable counts are one, unless RELION's use_gpu is off.
- Dry runs of schedule_jobs list each job's queue and GPUs.
- The write instructions tell the model to change gpu_ids for RELION
  jobs instead of forcing a 'gpus' parameter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
get_file_preview takes two optional arguments:

- slice='center': for MRC files (.mrc, .mrcs, .st, .ali, .rec), the
  central Z section instead of a montage. A tomogram written by Warp is
  flagged as an image stack, so the preview showed its first slices,
  mostly noise; the central section shows the particles. The section is
  described in meta['slice'], e.g. 'z=39 of 78'.
- max_size: preview size in pixels (64 to 1024; 512 for sections). The
  default stays 256.

Without them, the preview is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Found while running the ApoF tutorial through MCP:

- read_project_file(as_image=true) on a tomogram returned a 256-pixel
  montage of its first slices. It now asks EMhub for the central section
  of MRC files and for previews up to 512 pixels; an EMhub without that
  option sends its montage, and the note says so.
- get_job listed no inputs for jobs that had run: emwrap's run
  information has none then. The files of other jobs named in the
  parameters are listed instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Found while running the ApoF tutorial through MCP: when emwrap's
scheduler starts a scheduled job, it removes the job's scheduled mark,
submits it, and only then records it as launched. In between, the job
reads as 'saved' and get_project lists it as ready to run; running or
scheduling it then would submit it twice.

run_job and schedule_jobs now read the job's job.log and refuse a
'saved' job whose scheduler logged "Launching current job" within the
last two minutes, with a hint to check its status again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Renamed from sc_mcp_server so that its name shows it comes from devel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/apof-tutorial.md repeats the Warp ApoF tutorial with Claude Code
doing the work through this server: connecting the assistant, creating
the project, checking queues and GPUs, scheduling both parts, and asking
about the results. The conversations are from a real run on MPCDF phys
on 2026-10-23, with screenshots of the EMhub web interface taken during
the run (docs/images/apof-tutorial, 1.2 MB). Part 2's results are still
to come. Linked from the README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…7 Å)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@delarosatrevin

Copy link
Copy Markdown
Member

@sergiocruzleon , we were reviewing the PR, and we decided that it might be better to keep the MCP server as the emhub.mcp module, close to the EMhub philosophy. We reviewed some tools added in your branch that weren't covered there and implemented most of them.

I think we might need to test again with the jm_mcp branch and re-generate the tutorial files in the doc repository, not added here merging code and images.

Find below a detailed summary of what was already included in the branch jm_mcp.

EMhub MCP: processing tools ported from dev-sc_mcp_server into branch jm_mcp

The dev-sc_mcp_server branch has a separate MCP package (emhub-tomo-mcp/)
with 24 tools. Most of them already had an equivalent in emhub/mcp on
jm_mcp. This document summarises the gaps that were implemented (items 1-5)
and the decisions on the remaining proposals (items 8-10).

Status: implemented and unit tested (python -m unittest emhub.tests.test_mcp,
22 tests). Not yet tested against a live EMhub server. Not committed.

Implemented

1. Job types: processing_list_job_types, processing_describe_job_type

  • processing_list_job_types(include_hidden=False): lists the job types with
    id, label, output folder, whether they are shown in the processing menu
    (visible) and whether they have a form (has_form).

  • processing_describe_job_type(job_type, <project>, full_help=False): shows
    the parameters of a job type before any job of that type exists:

    • one entry per parameter, including params inside groups;
    • name, section, label, paramClass, default, choices, condition and
      important;
    • help, cut to 200 characters unless full_help;
    • the queue parameters configured on the server.

    Before this tool, the form was only available for an existing job
    (processing_get_job(include_form=True)), so creating a new job with
    processing_save_job(job_type=...) meant guessing parameter names.

  • Backend: new endpoint /api/get_job_types. It uses emwrap's
    ProcessingConfig.get_jobs(), is_job_visible() and get_job_form_file().
    describe_job_type uses the existing /api/get_session_run endpoint, with
    job_type and output=['form'].

2. processing_wait_for_jobs

  • processing_wait_for_jobs(run_ids, <project>, mode='all'|'any', timeout_s=120, poll_interval_s=15).
  • Waits until the jobs are finished, failed or aborted.
  • The timeout is capped at 600 s per call and the polling interval is kept
    between 5 and 120 s.
  • Returns satisfied, timed_out, waited_s, the current status of each
    job, and a note when it stopped early.
  • Returns at once if saved jobs make the condition impossible, since a saved
    job never finishes by itself.
  • Unknown job ids give an error.
  • It is an async tool: the polling sleeps and the REST calls don't block the
    server's event loop.

3. processing_validate_job

  • processing_validate_job(params, run_id | job_type, for_schedule=False, <project>).
  • Checks parameters against the job type's form without saving or running
    anything
    , and returns {'valid': bool, 'errors': [...]}.
  • For an existing job, the given params are merged into its saved ones.
  • With for_schedule, input files that parent jobs will produce may not exist
    yet.
  • Backend: new endpoint /api/validate_job, ported from dev-sc_mcp_server.
    It uses ProjectManager._readJobParams and _validateJobInputs. It is
    read-only and needs no edit right.

4. processing_get_project_summary

  • processing_get_project_summary(<project>, statuses=None, job_types=None, limit=100).
  • Returns:
    • job_count and status_counts;
    • failed: failed or aborted jobs;
    • active: scheduled, launched or running jobs;
    • ready_to_run: saved jobs whose parent jobs have all finished;
    • blocked: saved jobs with a failed or aborted parent;
    • the project labels;
    • the jobs (filtered by status and type) with their type, status, label,
      parents and children, plus jobs_omitted.
  • It is computed in the MCP server from get_session_workflow and
    get_project_labels; no backend change.

5. Better log reading in processing_get_job

New behaviour:

  • error_lines: with logs requested, the lines of the logs that look like
    errors, each prefixed with its log and line number (at most 30).
  • warnings: flags a job marked finished whose logs have error-like
    lines. emwrap can mark a job finished although part of it failed.
  • log_contains: returns the log lines containing a text
    (case-insensitive), with line numbers, instead of the last lines.
  • include_job_log: also returns job.log (scheduling and cluster
    submission) as joblog.

Backend:

  • /api/get_session_run accepts 'joblog' in output.
  • RelionRun.getInfo() now also returns the job status (e.g. 'Succeeded'),
    which the warning needs.

Limitations:

  • error_lines is a keyword heuristic (error, exception, traceback,
    failed, killed, out of memory, ...), so it can flag harmless lines.
  • EMhub cuts logs of more than 2000 lines to their first and last 1000 lines
    before sending them, so the middle of a long log is not searched.

Files changed

File Change
emhub/blueprints/api.py /get_job_types, /validate_job; joblog output in /get_session_run
emhub/data/processing/processing_relion/runs.py status in RelionRun.getInfo()
emhub/mcp/processing.py the new tools and helpers (_compact_form, _summarize_workflow, _error_lines, _grep)
emhub/mcp/README.rst tool list
emhub/tests/test_mcp.py 5 new tests: job types, validation, project summary, waiting, error lines

Not ported

  • The check that refuses to run or schedule a job while emwrap's scheduler is
    starting it
    (dev-sc_mcp_server commit 8d53ee4e).
    • Cause: emwrap's watcher removes the scheduled mark, submits the job and
      only then records it as launched. In between, the job reads as "saved",
      so launching it again would start it twice.
    • The race also affects the web UI, so it is better fixed in emwrap (mark
      the job launched before submitting it) than worked around in MCP.

Not implemented

8. Launch limits — to be discussed

Launch limits are launches per hour, a default queue, a maximum of GPUs per
job, a maximum of GPU jobs running at once, and no GPU jobs on the EMhub host.
Where to add the limit, and its impact on configuration and code, will be
discussed later. Points to consider:

  • Limits only in the MCP server (processing.py and settings read from
    environment variables in server.py):
    • about 150 lines;
    • processing_launch_job, processing_schedule_job and
      processing_copy_job would check the job's merged parameters (queue,
      GPUs) before calling EMhub;
    • the per-hour counter would be per process, and each user runs their own
      emh-mcp.
  • Scheduled jobs are launched later by emwrap's watcher (runJob in
    ProjectManager), not through MCP. Limits in MCP only control the moment of
    scheduling, and the web UI is not limited at all.
  • Limits in EMhub (launch_job/schedule_job) or emwrap (runJob) would
    cover every client. They could be keyed on the queue configuration in
    EMWRAP_CONFIG, at the cost of a larger emwrap change.

9. Audit log and per-project locks — does not seem to add much

  • Per-project locks: emwrap already serialises changes to a project with
    ProjectLock / _project_write, for every client. An MCP lock would only
    order the calls within one MCP process.
  • Audit log: an MCP-side log would only record MCP actions, in a file on
    the user's machine. If an audit trail is wanted later, logging in EMhub's
    handle_workflow(edit=True) would record every client, the web UI
    included, centrally.

10. Guide resources and prompts — maybe better placed somewhere else

  • diagnose_job and project_report prompts, and guides on the pipelines and
    queues as MCP resources.
  • Some MCP clients barely show resources and prompts.
  • The useful content may be better placed in the server instructions, the
    tool docstrings or the EMhub/emwrap documentation (or a skill), where it is
    kept in step with emwrap.

@delarosatrevin
delarosatrevin marked this pull request as draft October 23, 2026 21:33
Part 2 finished: all 22 jobs of the ApoF tutorial ran through the
assistant, ending at 2.90 Å after seven M refinement rounds (RELION's
Refine3D in part 1: 8.26 Å). Adds the assistant's final report, the
final map's central section, the final FSC curves and the finished
project, and completes the numbers: 5 h 36 min, 11 prompts, 138 tool
calls, $13.66.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@delarosatrevin

Copy link
Copy Markdown
Member

Already addressed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants