Skip to main content
Glama
Konjkov

casino-mcp

casino-mcp

PyPI Python CI Licence

Управляющий слой MCP для фортрановского кода квантового Монте-Карло CASINO: запускать расчёты, знать, что идёт, останавливать их и читать файл out как структурированные данные, а не отправлять 4000 строк текста в контекст модели.

Бета (0.2.0). Четыре управляющих инструмента и парсер out готовы и протестированы на реальном CASINO; инструмент, возвращающий физику модели, пока не поставляется. Интерфейсы могут ещё измениться до 1.0.

Что это такое, а что нет

У CASINO уже есть примитивы — opt_plan, runqmc --auto-continue, multirun, envmc, make_E_v_dt. Чего в нём нет — так это слоя между ними: результатов в машиночитаемом виде, памяти о том, что было запущено, и решений, которые принимаются между шагами («дисперсия вышла на плато?», «этот шаг по времени всё ещё в линейном режиме?»). Именно такой слой и есть этот пакет; три правила не дают ему отклоняться от честности:

  1. Ни одно число не порождается моделью. Каждое значение, возвращаемое инструментом, читается из файла и несёт строку, из которой оно взято. То, что CASINO не напечатал, возвращается как null с указанием причины, но никогда как догадка.

  2. Каждый результат воспроизводим из его записи. Запись задания фиксирует команду, число процессов и путь, размер и mtime выполнявшегося бинаря casino.

  3. Ничто разрушительное не подразумевается по умолчанию. Запуск отказывается начинаться в каталоге, где уже есть результаты, и отказывается ещё решительнее, если этот out — зафиксированные эталонные данные.

Здесь намеренно нет инструмента execute_shell(command). Каждый инструмент — это именованная операция CASINO с типизированными аргументами.

Related MCP server: qe2mcp

Установка

pip install casino-mcp          # needs Python 3.11+ and a working CASINO installation

Из клонированного репозитория:

pip install -e '.[dev]'

Пакет не включает в себя, не собирает и не заменяет CASINO. Он управляет runqmc, который остаётся исполняющей средой: определение архитектуры, варианты MPI, отправка в очередь пакетных заданий и файл блокировки — его работа, а не наша.

Зарегистрируйте его в Claude Code

.mcp.json, в рамках проекта:

{
  "mcpServers": {
    "casino": {
      "command": "casino-mcp",
      "args": ["serve"],
      "env": {
        "CASINO_HOME": "/home/you/bin/CASINO",
        "CASINO_ARCH": "linuxpc-gcc-parallel.openblas"
      }
    }
  }
}

Инструменты

инстурмент

возврящает

casino_run(workdir, nproc, version, restart, resume, unlock)

job_id, pid, workdir, command, бинарный отпечаток, что удалил restart

casino_status(job_id)

running / finished / failed / stopped / unknown, pid, runtime, exit code

casino_stop(job_id, timeout)

что получило сигнал, итоговый статус, что сделал haltqmc

casino_list_jobs(limit)

все известные задания, сначала самые свежие

Тип расчёта (vmc, vmc_opt, vmc_dmc, …) берётся из файла input в workdir; отдельного инструмента на каждый тип нет, потому что это умнож ало бы поверхность без добавления возможностей.

Запуск, остановка и продолжение расчёта идут через собственные скрипты CASINO — и только через них: runqmc запускает, haltqmc завершает и убирает за собой, runqmc --continue (или обычный runqmc по input, который переписал haltqmc -u) продолжает. Здесь ничто не перемещает конфигурационные файлы, не редактирует input и не решает, что делать недо конца завершённому расчёту.

Каталог, в котором уже есть out

runqmc дописывает в out, vmc.hist и dmc.hist, а не заменяет их, поэтому зауск двжды в одном катаоге даёт файлы, в которых два расчёта склеены вместе. По умолчанию это зарещено; обойти можно двумя способами — они противоположны, так что передайте один:

restart=true

удалить то, что оставил предыдущий запуск, и начать с начала. out, out_part.N, файлы .hist, config.in/config.out, correlation.out.N, parameters.N.casl, saved_part_N/. Входные данные остаются: input, волновая функция, псевдопотенциалы, correlation.data, parameters.casl. Каждое удалённое имя возвращается в ответе под ключом removed.

resume=true

продолжить прерванный расчёт с того места, где он остановился. Какой из двух путей продолжения CASINO будет использован, определяется по out, а не выбирается здесь — см. ниже.

В командно строке это --restart и --resume; для второго принимается также --continue — так его называет runqmc. Параметр инструмента так назван быть не может: continue — ключевое слово Python.

Остановка расчёта и его продолжение

casino_stop отправляет SIGTERM процессам casino этого задания и больше никому — тот же сигнал, что посылает haltqmc -k, но haltqmc делает pkill -x casino по всей учётной записи, что остановило бы все остальные задания на машине. mpirun помещает каждый ранг в отдельную группу процессов, поэтому ранги находятся по идентификатору сеанса: сеанс принадлежит запускающему процессу, и всё дерево делит его. Сам runqmc остаётся живым, чтобы завершить свой эпилог, и только задание, всё ещё работающее после timeout, получает сигнал в свою группу процессов и затем уничтожается.

Затем каталог передаётся haltqmc -f -u — именно это делает остановленный расчёт пригодным для продолжения: config.out становится config.in, файлы блокировки и маркеры удаляются, а input переписывается под оставшуюся работу — newrun : F, вычитаются завершённые блоки, тип расчёта переводится на следующий этап. Ответ сообщает, что было сделано, под ключом halt. input в том виде, каким он был до этого, копируется в каталог задания, а halt.input_saved указывает, куда.

Какой маршрут продолжения выберет resume=true, решает последний запуск в out:

CONTINUATION INFO: in out

runqmc --continue. CASINO пишет этот блок только тогда, когда останавливается сам по max_cpu_time или max_real_time; runqmc применяет его и архивирует завершённый сегмент в saved_part_N/.

такого блока нет

обычный runqmc по input, который переписал haltqmc. Так продолжается прерванный расчёт — --continue лишь остановился бы с ошибкой из-за отсутствующей информации о продолжении.

расчёт дошёл до своего конца

отказ: продолжать нечего.

restart=true отклоняется для каталога, в чьём input указано newrun : F, потому что перезапуск удаляет config.in, который CASINO затем потребует. Сначала верните сохранённый input.

Командная строка

Та же среда выполнения без модели в цикле — а это также способ отладить сервер:

casino-mcp config                  # the resolved configuration, and the files it came from
casino-mcp run ./calc -p 4         # start a calculation
casino-mcp run ./calc --restart    # ... after deleting what an earlier run left there
casino-mcp run ./calc --continue   # ... or carrying that run on instead
casino-mcp status 20260823-164511-qobn
casino-mcp stop   20260823-164511-qobn   # stop the run, then hand the directory to haltqmc
casino-mcp jobs                    # the registry, newest first
casino-mcp parse ./calc            # the `out` file as JSON
casino-mcp serve                   # the MCP server on stdio

Каждая подкоманда выводит JSON и завершается с ненулевым кодом, если в этом JSON есть error.

Конфигурация

Конфигурационного файла нет. MCP-сервер настраивается там, где он зарегистрирован, — в блоке env указанного выше .mcp.json, — а собственные переменные CASINO сохраняют свои имена, так что их достаточно настроить один раз для обоих уровней:

variable

CASINO_HOME

корень установки CASINO (по умолчанию ~/bin/CASINO)

CASINO_ARCH

целевая сборка,каталог в bin_qmc; используется для фиксации того, какой бинарь запускал задание

CASINO_RUNQMC

явный путь к runqmc; иначе PATH, затем $CASINO_HOME/bin_qmc/runqmc

CASINO_HALTQMC

явный путь к haltqmc; иначе PATH, затем $CASINO_HOME/bin_qmc/haltqmc

CASINO_MCP_STATE_DIR

реестр заданий; иначе $XDG_STATE_HOME/casino-mcp

CASINO_MCP_FORBID

каталоги, которых ни один расчёт не должен касаться, разделитель : — как у PATH

Всё остальное — один MPI-процесс, бинарь opt, двадцать секунд на самостоятельное завершение остановленного задания, минута на уборку haltqmc, двести хранимых записей о заданиях — это константы в settings.py. casino-mcp config выводит, что сервер использовал бы прямо сейчас и какая переменная это определила; запустите её в первую очередь, если вызов инструмента получает отказ.

CASINO_MCP_FORBID — единственная защита, которую нельзя обойти при конкретном вызове. restart=true/resume=true и unlock=true снимают две другие; каталог, указанный здесь, вообще нельзя использовать для запуска — именно поэтому это правильное место для дерева зафиксированных эталонных расчётов.

Как это работает

Claude Code ──stdio──> server.py ──spawn──> launcher.py ──> runqmc ──> mpirun ──> casino
                          │                     │
                          │                     └─ writes status.json (exit code, end time)
                          └─ reads/writes jobs.json + one directory per job

Состояние хранится вне расчёта, в $XDG_STATE_HOME/casino-mcp/:

jobs.json                    index: job_id -> record
jobs/<job_id>/meta.json      what was launched, frozen at spawn
jobs/<job_id>/status.json    written by the launcher when the run ends
jobs/<job_id>/runqmc.log     runqmc's own output (not CASINO's `out`)
jobs/<job_id>/input.before_halt   the input as it was, kept when a stop rewrites it

Каталог расчёта получает только то, что туда кладёт CASINO.

Зачем нужен запускающий процесс. runqmc — это bash-скрипт, который выполняет через exec mpirun -np N casino; отправка сигнала его pid осиротит дерево. Запускающий процесс работает в собственном сеансе — именно это делает дерево идентифицируемым: killpg достаёт до runqmc и mpirun, а идентификатор сеанса находит ранги, которые mpirun поместил в отдельные группы процессов. Его код завершения переживает перезапуск MCP-сервера, а вывод runqmc идёт в лог вместо потока JSON-RPC. Повторно использованный pid не может сойти за живое задание: сравнивается время старта из /proc/<pid>, а зомби не считается работающим.

Парсер out

parse_out — обычная функция без MCP и без зависимостей. Файл out — это последовательность фаз, а не один результат: vmc_opt записывает по фазе VMC и OPTIMIZATION за каждый цикл, vmc_dmc записывает VMC, уравновешивание DMC и накопление статистики DMC. Поэтому функция возвращает phases, а result указывает на последнюю фазу, которая содержит энергию.

from casino_mcp.parse_out import parse_out

parsed = parse_out('./calc')
parsed['result']['energy']  # {'value': -2.861829862553, 'error': 0.000659077167, 'line': 237}

Единственное вычисляемое число в нём — ошибка выборочной дисперсии для прогона из одного блока; CASINO его не печатает. Оно берётся из единственного блока точно так же, как это делает envmc, и помечается как derived. Ничто не обращается к envmc или endmc как к внешним командам во время выполнения — endmc неправильно разбирает числа в локали, отличной от C.

Тесты

pytest                      # 158 tests, ~5 s, no CASINO needed

Модульные тесты запускаются где угодно: парсер проверяется поле за полем на пяти реальных файлах out из tests/data/ — для каждого прилагается input, который его породил, — и на всех восемнадцати расчётах из examples/; при этом запускающий процесс, группа процессов и защитные ограничения проверяются на фиктивном shell-скрипте runqmc.

pytest -m integration

Интеграционному набору нужен настоящий CASINO, но ничего за пределами этого репозитория. Он сверяет parse_out с собственным envmc от CASINO для каждого out в examples/, перезапускает всё дерево на установленном бинарнике и управляет сервером через реальный stdio MCP, запуская и останавливая настоящие расчёты VMC.

examples/ содержит восемнадцать расчётов, подобранных как покрытие настроек запуска CASINO: каждый тип запуска, тип базиса, оптимизатор и опция волновой функции встречаются хотя бы раз; в него также входят два файла, на которых парсер незаметно ошибается: расчёт, так и не напечатавший энергию, и расчёт, прерванный между циклами оптимизации. В examples/README.md сказано, для чего нужен каждый из них.

Они короткие и с фиксированным зерном, поэтому дерево одновременно служит проверкой самого CASINO: перезапустите его на новом релизе — и любая строка, которую читает парсер и которая была переименована или удалена, будет названа, а не молча превратится в None. Проверяется только это — перемещённые числа сообщаются человеку на суждение.

python tools/refresh_examples.py --nproc 4     # run the tree, report, touch nothing
python tools/refresh_examples.py --nproc 4 --write   # adopt the new output

tools/protocol_dump.py вручную общается по JSON-RPC без SDK и печатает каждую строку в обоих направлениях. Прочитайте его, прежде чем добавлять инструмент.

Лицензия

MIT.

Available Tools

6 tools
casino_list_jobsC

Every known job, newest first, with its current state.

NameRequiredDescriptionDefault
limitNo

Output Schema

NameRequiredDescription

No output parameters

TDQS

C2.7/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden, but it does not state whether the operation is read-only or requires authentication. More importantly, it claims 'Every known job' while the schema shows a default limit of 20, suggesting the list is limited and not actually every job. This creates a transparency gap about the tool's real behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, compact sentence with no wasted words. It front-loads the core subject ('Every known job') and delivers the key dimensions (order and state) efficiently. For a simple list tool, this is an ideal length and structure.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description is incomplete for a tool with no annotations and an underspecified schema. It does not explain the limit parameter's effect, the read-only nature, or when to use it relative to siblings. Although an output schema exists, key operational context is missing, leaving an agent uncertain about how to invoke it correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The only parameter, 'limit', has zero schema description coverage, and the description does not mention it at all. The description's phrase 'Every known job' actively obscures the fact that the limit parameter controls how many jobs are returned. The description provides no semantic help for the parameter.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly indicates that the tool lists all known jobs with their current state, newest first. It implies a listing operation and distinguishes itself from siblings like casino_status or casino_results by covering all jobs rather than a specific one. It lacks a direct verb like 'list', but the intended purpose is unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided about when to use this tool versus the sibling tools. There is no mention of use cases, exclusions, or alternatives such as casino_status for a single job's status. The description only states what the tool does, not when to choose it.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

casino_prepareA

Copy a calculation into a new directory and write the input for the next run in it.

This is how a calculation becomes the next one: optimise a wave function, then prepare a vmc_dmc directory beside it; halve the timestep into another; change the target weight into a third. A copy rather than an edit, because a number whose input was overwritten in place can no longer be reproduced, and because casino_run refuses a directory that already holds a run -- rightly.

What is copied is what a calculation is given and never what a run produced: input, the orbital file, correlation.data, parameters.casl, the pseudopotentials, and config.in (which a dmc-only or opt runtype reads as an input). Not out, not the .hist files, not config.out. A symlinked orbital file is copied by content, so the new directory stands on its own.

runtype: the runtype the new directory is for -- vmc, vmc_opt, opt, vmc_dmc, vmc_dmc_equil, dmc_dmc, dmc_equil, dmc_stats. Every keyword that runtype needs and the source input does not set is filled from a working default; every keyword the source does set is kept, so the electron count, the basis and any hand tuning survive. Leave it empty to keep the source's runtype and only apply overrides. overrides: keywords to set, as {name: value}, and they win over both the source and the defaults. A null value deletes the keyword; a value containing newlines is written as a %block (that is how opt_plan and npcell are set). Values are written verbatim, so booleans are 'T' and 'F' as CASINO spells them. jastrow: the terms of a blank Jastrow factor to write into the new directory -- ['u', 'chi', 'f'] for the usual one, ['u'] for a system with no atoms. This is for the first calculation of a chain, the one whose directory holds an orbital file and nothing else: use_jastrow : T needs a correlation.data, no CASINO utility writes one, and the manual's own instruction is to copy an example and delete its numbers by hand. Every coefficient starts at zero, which is what the first optimisation cycle is for. Leave it unset when the source already has a correlation.data; asking for both is refused, because a blank Jastrow would discard an optimised one. Finite systems only so far: a periodic Jastrow wants a P term, whose stars come from CASINO's own make_p_stars. backflow: the terms of a blank backflow function, in the same file -- ['eta', 'mu', 'phi'] for the usual one. It goes with backflow : T in the input, and the two blocks are written together for a calculation that wants both. The electron-nucleus cusp type of each set is not a setting: it is read off the pseudopotentials in the directory, 1 for a bare nucleus and 0 behind a pseudopotential, because CASINO believes the flag without checking it. No AE CUTOFFS section is written -- it is optional, and CASINO chooses the lengths itself. jastrow_settings: the shape of both blocks, where the defaults are not wanted. Jastrow: trunc_order (3), n_u (8), n_chi (8), n_f_en (3), n_f_ee (3), spin_dep_u (1), spin_dep_chi (0), spin_dep_f (1), cusp_chi (0), cutoff_u / cutoff_chi / cutoff_f (0, which CASINO reads as "use your own default"), no_dup_u (0), no_dup_chi (0), optimizable (1, the cutoffs). Backflow: bf_trunc_order (3), n_eta (9), n_mu (9), n_phi_en (3), n_phi_ee (3), spin_dep_eta (1), spin_dep_mu (0), spin_dep_phi (1), cutoff_eta / cutoff_mu / cutoff_phi (0), irrotational (0), cusp_bf (-1, meaning derive it from the pseudopotentials).

Nothing is written unless the result would actually run: the keyword combinations CASINO only rejects at run time are checked first (an optimisation sample smaller than the DMC target weight, opt_backflow without backflow, a missing mandatory keyword), and so is the presence of every file the input tells CASINO to read. A refusal names the problems and creates no directory. What is legal but probably unintended -- a dtdmc still at CASINO's placeholder default, dmc_stats_nstep not divisible by its block count, keywords left over from the runtype this was copied from -- comes back in warnings and does not stop it.

NameRequiredDescriptionDefault
destYes
sourceYes
jastrowNo
runtypeNo
backflowNo
overridesNo
jastrow_settingsNo

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.8/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description fully carries the behavioral burden: which files are copied, which are excluded, symlink handling, default filling, validation checks, refusal behavior, warnings, and precedence rules. This is exceptionally transparent.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is long, but every paragraph earns its place given the domain complexity. It is front-loaded with purpose, then systematically covers file selection, parameters, and validation behavior without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a 7-parameter tool with no annotations, this description is complete: all parameters are explained, valid runtypes are enumerated, defaulting and overrides are specified, and refusal/warning behavior is disclosed. The presence of an output schema covers return-value specifics.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate and does so thoroughly: runtype values and defaults, overrides precedence and %block behavior, jastrow/backflow semantics, and jastrow_settings defaults. Even the required source/dest parameters are clear from context.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The first sentence states the exact action: copy a calculation into a new directory and write the input for the next run. The workflow explanation and examples make it clearly distinct from sibling tools like casino_run or casino_status.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives strong workflow context ('This is how a calculation becomes the next one') and concrete examples, and it explains why copying rather than editing is required because casino_run refuses a directory that already holds a run. It stops short of explicitly naming when-not-to-use alternatives such as 'use casino_run to execute instead'.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

casino_resultsA

Physics out of a job's files: energies, error bars, variance, per-block numbers.

Reads out and returns it as phases, because a CASINO run is a sequence of them and not one result: vmc_opt writes a VMC and an optimization phase per cycle, vmc_dmc writes VMC, DMC equilibration and DMC statistics accumulation. result points at the number that is this run's answer, and every value carries the file and line it was read from. Nothing is computed here that CASINO did not print, and a value it did not print comes back as null with the reason.

A DMC run that has not ended is readable too, and this is the only way to read one: CASINO writes the mixed estimators into out at the very end, and until then the current estimate lives in dmc.status, which it rewrites after every statistics block and deletes when the run finishes. When that file is there it is parsed into dmc_status and result points at it, so a running job answers with the estimate as of its last block -- and never with the VMC energy of the configuration-generation phase, which is the trial wave function's and not the calculation's. A run stopped by casino_stop keeps its dmc.status, so the last estimate it reached survives the stop.

While the run is still equilibrating there is no DMC energy anywhere yet, and result then says so rather than answering with an earlier phase.

NameRequiredDescriptionDefault
job_idYes

Output Schema

NameRequiredDescription

No output parameters

TDQS

A3.8/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full behavioral burden and does so thoroughly. It explains that values come from CASINO-printed data, that missing values return null with a reason, that running DMC results are read from dmc.status, that dmc.status is deleted on completion, and that casino_stop preserves the last estimate. This is rich, non-obvious behavioral context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is long but information-dense, with each paragraph covering a distinct behavioral area: output contents, phase semantics, running jobs, and equilibration. The structure is front-loaded with purpose and then deepens into edge cases. The awkward opening phrase 'Physics out of a job's files' slightly reduces clarity but does not waste space.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given that an output schema exists and the tool has only one parameter, the description is unusually complete. It covers completed runs, running DMC runs, stopped runs, equilibration, value provenance, and the meaning of `result`. An agent has enough context to invoke the tool correctly and interpret its results in most scenarios.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has one required parameter, job_id, with 0% schema description coverage, and the tool description never mentions job_id explicitly. It refers to 'a job's files' and 'this run,' but it does not explain how job_id selects the job, where to obtain valid job IDs, or any constraints. Because schema coverage is low, the description was expected to compensate and did not.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states that the tool reads a job's `out` file and returns energies, error bars, variance, per-block numbers, and phases, which clearly identifies it as a results-reading tool. It also explains the `result` field as the run's answer, giving concrete purpose. It does not explicitly name sibling distinctions, but the resource and operations are clear.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides useful conditions for when this tool is appropriate, especially for running DMC runs, saying it is 'the only way to read one.' It also covers stopped runs and equilibration states. However, it never explicitly contrasts the tool with casino_status or casino_list_jobs, so alternative routing is only implied rather than stated.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

casino_runA

Start a CASINO calculation in workdir and return immediately.

The runtype (vmc, vmc_opt, vmc_dmc, ...) comes from the input file in workdir; this tool only decides how the binary is launched. The calculation keeps running after the call returns and after this server is restarted.

A directory that already holds an out is refused, because runqmc appends to it and the result is two runs in one file. restart and resume are the two ways past that, and they are opposites -- pass one.

workdir: directory holding input and the wave function files. nproc: number of MPI processes (vmc_nstep in input is the total over all of them). version: binary flavour, 'opt' or 'debug'. restart: delete out and everything else the earlier run left -- .hist files, configs, optimisation output -- and start the calculation over. Inputs are kept. Destructive: config.in goes too, so what could have been continued no longer can be. Refused on a directory whose input haltqmc has set up to continue (NEWRUN : F), because CASINO then wants the config.in this would delete; casino_stop keeps a copy of the input as it was, and the reply to the stop says where. resume: carry the interrupted run on, keeping the work already done. Which of CASINO's two continuation routes that takes is read out of out, not chosen here: a run that CASINO stopped on max_cpu_time / max_real_time is continued by runqmc --continue, and a run that casino_stop halted is continued by a plain runqmc over the input that haltqmc -u rewrote. The reply says which one under resume. A run that reached its own end is refused -- there is nothing to continue. unlock: clear a stale .runqmc.lock left by a runqmc instance that died.

NameRequiredDescriptionDefault
nprocNo
resumeNo
unlockNo
restartNo
versionNoopt
workdirYes

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.8/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden, and it delivers: it discloses that the calculation outlives the call and server restart, that `out` is appended to and can corrupt results, that restart is destructive to `config.in` and optimization output, and how resume behaves under different halting conditions. This is deep, honest behavioral disclosure.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is long but every sentence earns its place. It is front-loaded with the core purpose, then organizes the non-obvious behavioral details and parameter semantics in a structured, scannable way. The density is justified by the tool's complexity and destructive options.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given a 6-parameter tool with no annotations, the description is exceptionally complete: it covers prerequisites, launch semantics, background persistence, destructive behavior, failure conditions, and parameter interactions. The presence of an output schema relieves it from detailing return values, so nothing critical is missing for correct invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate, and it does thoroughly. Every parameter — workdir, nproc, version, restart, resume, unlock — gets meaningful explanation beyond its name, including relationships like nproc counting total vmc_nstep, version being a binary flavour, and the precise effects of restart versus resume.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description opens with a precise verb and resource: 'Start a CASINO calculation in workdir and return immediately.' It clarifies that the runtype comes from the input file and that this tool only controls binary launch, making it easy to distinguish from siblings like casino_prepare, casino_status, and casino_stop.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It gives strong when-to-use and when-not-to-use guidance: directories with existing `out` are refused, restart and resume are opposites, resume is refused for completed runs, and restart is refused when NEWRUN : F is set. It does not explicitly name sibling alternatives for common flows, but the contextual sibling list makes the intended role clear.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

casino_statusA

State of one job: running / finished / failed / stopped, pid, runtime in seconds, exit code.

NameRequiredDescriptionDefault
job_idYes

Output Schema

NameRequiredDescription

No output parameters

TDQS

A3.6/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are present, so the description must carry the behavioral burden. It does disclose the status vocabulary and returned metrics, and 'state of one job' strongly implies a read-only query. However, it does not explicitly state that it has no side effects, how unknown or expired job IDs are handled, or whether it is safe to poll repeatedly.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single sentence with no filler. It front-loads the core scoping ('State of one job') and then lists the concrete status and metric fields, so every word adds value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a low-complexity one-parameter status query, the description is largely complete: it defines the job scope and the returned state fields, and the output schema covers the return contract. The main omissions are explicit usage routing and side-effect disclosure, but the tool is simple enough that the given information allows a correct call.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must add meaning to job_id. It adds minimal context by indicating the parameter refers to the specific job whose state is checked, but it does not mention job_id by name, explain how to obtain a valid value, or provide any format guidance beyond the schema's string type.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly identifies the tool as reporting the state of a single job and enumerates the key fields returned (status, pid, runtime, exit code). The phrase 'one job' helps separate it from casino_list_jobs, but it does not explicitly contrast with casino_results or other siblings.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Usage is implied rather than stated: an agent can infer that this tool is for checking an individual job's status after invoking casino_run. There is no explicit guidance about when to use it instead of casino_results, casino_stop, or casino_list_jobs, and no mention of prerequisites such as having a valid job_id.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

casino_stopA

Stop a running calculation and leave its directory ready to be continued.

SIGTERM goes to this job's casino processes, as haltqmc -k does for the whole account, so runqmc stays alive to finish writing out. CASINO has no graceful-halt signal: the blocks it had finished stay in out, vmc.hist and dmc.hist, the current block is lost. Then haltqmc -f -u tidies the directory -- config.out to config.in, the lock file, and input rewritten for the work that is left -- so casino_run(workdir, resume=true) carries this calculation on.

timeout: seconds the job gets to end on its own before the process group is killed.

NameRequiredDescriptionDefault
job_idYes
timeoutNo

Output Schema

NameRequiredDescription

No output parameters

TDQS

A4.5/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden and succeeds. It details that SIGTERM targets the job's casino processes, that runqmc survives to write output, that the current block is lost, and that haltqmc -f -u tidies the directory for resumption. It also explains the timeout fallback behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core purpose and then adds only high-signal behavioral details. Every sentence contributes meaningful operational knowledge without repetition or filler.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a side-effect-heavy tool with no annotations, the description is remarkably complete: it covers signal behavior, persistence of completed data, loss of current block, directory cleanup, resumption path, and timeout semantics. An output schema is present, so explaining return values is not necessary.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, so the description must compensate. It fully explains timeout as the seconds a job gets before its process group is killed, but job_id is left to its schema title and the contextual phrase 'running calculation.' The main parameter is not explicitly defined or sourced.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description opens with a specific verb and resource: 'Stop a running calculation and leave its directory ready to be continued.' This clearly distinguishes casino_stop from the sibling tools casino_run, casino_prepare, casino_status, casino_results, and casino_list_jobs.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description clearly establishes the tool's purpose for stopping a running calculation and contrasts it with haltqmc -k's account-wide behavior, implying this tool is job-scoped. It does not explicitly enumerate when to use it over siblings, but the intended use is unambiguous in context.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 6 tool updatesv0.4.0
    • First observedcasino_list_jobs
    • First observedcasino_prepare
    • First observedcasino_results
    • First observedcasino_run
    • First observedcasino_status
    • First observedcasino_stop

TDQS

A3.9/5.0

Scored across 6 tools

Disambiguation5/5

Each tool addresses a distinct lifecycle stage: preparing a directory, launching/interrupting a run, listing/checking jobs, and extracting physics results. Status and list_jobs are adjacent, but one is explicitly per-job detail while the other is an overview, so there is no real ambiguity.

Naming Consistency4/5

All tools share the casino_ prefix and use snake_case, but the pattern mixes simple verbs (run, prepare, stop), a verb-object phrase (list_jobs), and bare nouns (status, results). This is readable and predictable, though not a uniform verb_noun convention.

Tool Count5/5

Six tools is a well-scoped set for a job-management server. Each tool covers a necessary action without redundancy, and the count sits comfortably in the ideal 3-15 range.

Completeness5/5

The tool surface covers the full CASINO workflow: prepare a calculation, run or restart it, monitor it, stop it, and retrieve physics results. Missing cleanup or job-forgetting operations are not essential to the stated purpose.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    C
    maintenance
    Converts Quantum ESPRESSO output files to structured JSON and serves them via an HTTP API for use with MCP clients.
    MIT
  • A
    license
    A
    quality
    A
    maintenance
    Durable MCP server for managing long-running jobs locally, over SSH, or on Slurm clusters. Jobs survive client disconnects and return exit codes, bounded logs, and JSON artifacts.
    11
    28 PyPI
    1
    MIT
  • A
    license
    A
    quality
    C
    maintenance
    Enables headless control of DHI MIKE Zero, including launching and batch-running simulations, monitoring job progress and logs, and reading/plotting simulation results from DFS and RES1D files.
    15
    MIT