Skip to main content
Glama
casino-mcp

casino-mcp

casino-mcp

PyPI Python CI Licence

Eine MCP-Steuerungsebene für den Fortran-CASINO-Quanten-Monte-Carlo-Code: Läufe starten, wissen, was läuft, sie stoppen und eine out-Datei als strukturierte Daten lesen, statt 4000 Zeilen Text in den Kontext eines Modells zu schicken.

Beta (0.2.0). Die vier Steuerungs-Tools und der out-Parser sind fertig und gegen ein echtes CASINO getestet; das Tool, das die Physik an das Modell zurückgibt, ist noch nicht ausgeliefert. Die Schnittstellen können sich vor 1.0 noch ändern.

Was es ist, und was es nicht ist

CASINO hat bereits die Grundbausteine — opt_plan, runqmc --auto-continue, multirun, envmc, make_E_v_dt. Was ihm fehlt, ist die Ebene dazwischen: maschinenlesbare Ergebnisse, eine Erinnerung daran, was ausgeführt wurde, und die Entscheidungen, die zwischen den Schritten liegen („hat die Varianz ein Plateau erreicht?“, „ist dieser Zeitschritt noch im linearen Bereich?“). Diese Ebene ist dieses Paket, und drei Regeln halten es ehrlich:

  1. Keine Zahl wird vom Modell erzeugt. Jeder Wert, den ein Tool zurückgibt, wird aus einer Datei gelesen und trägt die Zeile, aus der er stammt. Was CASINO nicht gedruckt hat, wird als null mit einer Begründung zurückgegeben, nie als Schätzung.

  2. Jedes Ergebnis ist aus seinem Datensatz reproduzierbar. Ein Jobdatensatz friert den Befehl, die Prozessanzahl sowie Pfad, Größe und mtime des ausgeführten casino-Binärprogramms ein.

  3. Nichts Destruktives passiert implizit. Ein Lauf weigert sich, in einem Verzeichnis zu starten, das bereits Ergebnisse enthält, und weigert sich noch entschiedener, wenn diese out-Datei festgeschriebene Referenzdaten enthält.

Es gibt bewusst kein execute_shell(command)-Tool. Jedes Tool ist eine benannte CASINO-Operation mit typisierten Argumenten.

Related MCP server: qe2mcp

Installation

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

Aus einem Checkout:

pip install -e '.[dev]'

Das Paket bündelt, kompiliert oder ersetzt CASINO nicht. Es steuert runqmc, das die Laufzeit bleibt: Architekturerkennung, MPI-Varianten, Batch-Queue-Submission und die Sperrdatei sind seine Aufgabe, nicht unsere.

Bei Claude Code registrieren

.mcp.json, Projektbereich:

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

Tools

Tool

Rückgabe

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

job_id, pid, workdir, command, Binärstempel, was restart entfernt hat

casino_status(job_id)

running / finished / failed / stopped / unknown, pid, Laufzeit, Exit-Code

casino_stop(job_id, timeout)

was signalisiert wurde, Endstatus, was haltqmc getan hat

casino_list_jobs(limit)

jeder bekannte Job, neueste zuerst

Der Runtyp (vmc, vmc_opt, vmc_dmc, …) stammt aus der Datei input in workdir; es gibt kein Tool pro Runtyp, weil das die Oberfläche vergrößert, ohne eine Fähigkeit hinzuzufügen.

Starten, Stoppen und Fortsetzen einer Berechnung laufen alle über CASINOs eigene Skripte, und nur über sie: runqmc startet, haltqmc beendet und räumt auf, runqmc --continue oder ein einfaches runqmc über das von haltqmc -u neu geschriebene input führt fort. Nichts hier verschiebt eine Konfigurationsdatei, bearbeitet eine input-Datei oder entscheidet, was eine halb fertige Berechnung als Nächstes tun soll.

Ein Verzeichnis, das bereits eine out-Datei enthält

runqmc hängt an out, vmc.hist und dmc.hist an, statt sie zu ersetzen; ein zweiter Lauf im selben Verzeichnis erzeugt also Dateien, die aus zwei zusammengeklebten Läufen bestehen. Das wird standardmäßig verweigert, und es gibt zwei Wege daran vorbei — Gegensätze, also geben Sie genau einen an:

restart=true

Löschen, was der frühere Lauf hinterlassen hat, und neu beginnen. out, out_part.N, die .hist-Dateien, config.in/config.out, correlation.out.N, parameters.N.casl, saved_part_N/. Die Eingaben bleiben erhalten: input, die Wellenfunktion, die Pseudopotenziale, correlation.data, parameters.casl. Jeder gelöschte Name erscheint in der Antwort unter removed.

resume=true

Den unterbrochenen Lauf dort fortsetzen, wo er gestoppt wurde. Welche der beiden CASINO-Fortsetzungsrouten dabei zum Zug kommt, wird aus out ausgelesen, nicht hier gewählt — siehe unten.

In der Befehlszeile sind das --restart und --resume, und für Letzteres wird auch --continue akzeptiert, so wie runqmc es nennt. Der Tool-Parameter kann nicht so geschrieben werden: continue ist ein Python-Schlüsselwort.

Einen Lauf stoppen und fortsetzen

casino_stop sendet SIGTERM an die casino-Prozesse dieses Jobs und an sonst nichts — dasselbe Signal, das haltqmc -k sendet, nur dass es bei haltqmc ein pkill -x casino über das gesamte Konto ist, das jeden anderen Job auf der Maschine beenden würde. mpirun setzt jeden Rang in eine eigene Prozessgruppe; die Ränge werden also über die Session-ID gefunden: Die Session gehört dem Launcher, und der gesamte Baum teilt sie. runqmc selbst bleibt am Leben, um seinen Epilog zu beenden, und nur ein Job, der nach timeout immer noch läuft, bekommt ein Signal an seine Prozessgruppe und wird dann beendet.

Danach wird das Verzeichnis an haltqmc -f -u übergeben, was der Teil ist, der einen gestoppten Lauf fortsetzbar macht: config.out wird zu config.in, die Sperr- und Markierungsdateien verschwinden, und input wird für die verbleibende Arbeit neu geschrieben — newrun : F, die fertigen Blöcke werden abgezogen, der Runtyp rückt zur nächsten Stufe vor. Die Antwort enthält unter halt, was getan wurde. Das input, wie es vorher war, wird in das Jobverzeichnis kopiert, und halt.input_saved gibt an, wohin.

Welche Fortsetzungsroute resume=true dann nimmt, entscheidet der letzte Lauf in out:

CONTINUATION INFO: in out

runqmc --continue. CASINO schreibt diesen Block nur, wenn es selbst wegen max_cpu_time oder max_real_time anhält; runqmc wendet ihn an und archiviert das fertige Segment in saved_part_N/.

kein solcher Block

ein einfaches runqmc über das input, das haltqmc neu geschrieben hat. So wird ein unterbrochener Lauf fortgesetzt — --continue würde nur mit einem Fehlerstopp wegen der fehlenden Continuation-Info enden.

der Lauf hat sein eigenes Ende erreicht

verweigert: Es gibt nichts fortzusetzen.

restart=true wird für ein Verzeichnis verweigert, dessen input newrun : F angibt, weil ein Neustart das config.in löscht, das CASINO dann verlangt. Legen Sie zuerst das gespeicherte input zurück.

Befehlszeile

Dieselbe Laufzeitumgebung ohne Modell in der Schleife — auf diese Weise debuggen Sie auch den Server:

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

Jeder Unterbefehl gibt JSON aus und beendet sich mit einem Exit-Code ungleich null, wenn dieses JSON ein error enthält.

Konfiguration

Es gibt keine Konfigurationsdatei. Ein MCP-Server wird dort konfiguriert, wo er registriert ist — im env-Block der .mcp.json oben — und CASINOs eigene Variablen behalten ihre Namen; sie einmal zu setzen, konfiguriert beide Ebenen:

Variable

CASINO_HOME

Wurzel der CASINO-Installation (Standard ~/bin/CASINO)

CASINO_ARCH

Build-Ziel, das Verzeichnis unter bin_qmc; dient als Stempel, welches Binärprogramm ein Job ausgeführt hat

CASINO_RUNQMC

expliziter Pfad zu runqmc; sonst PATH, dann $CASINO_HOME/bin_qmc/runqmc

CASINO_HALTQMC

expliziter Pfad zu haltqmc; sonst PATH, dann $CASINO_HOME/bin_qmc/haltqmc

CASINO_MCP_STATE_DIR

die Job-Registry; sonst $XDG_STATE_HOME/casino-mcp

CASINO_MCP_FORBID

Verzeichnisse, die kein Lauf je berühren darf, :-getrennt wie PATH

Alles andere — ein MPI-Prozess, das opt-Binärprogramm, zwanzig Sekunden, die ein gestoppter Job zum selbstständigen Beenden bekommt, eine Minute für haltqmc zum Aufräumen, zweihundert aufbewahrte Jobdatensätze — ist eine Konstante in settings.py. casino-mcp config gibt aus, was der Server gerade verwenden würde und welche Variable das festgelegt hat; führen Sie es zuerst aus, wenn ein Tool-Aufruf verweigert wird.

CASINO_MCP_FORBID ist die einzige Schutzmaßnahme ohne Übersteuerung pro Aufruf. restart=true/resume=true und unlock=true entsperren die anderen beiden; ein hier gelistetes Verzeichnis kann überhaupt nicht für einen Lauf verwendet werden, was es zum richtigen Ort für einen Baum festgeschriebener Referenzrechnungen macht.

So funktioniert es

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

Der Zustand liegt außerhalb der Berechnung, unter $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

Das Berechnungsverzeichnis bekommt immer nur das, was CASINO dort ablegt.

Warum ein Launcher-Prozess. runqmc ist ein Bash-Skript, das mpirun -np N casino per exec ausführt; das Signalisieren seiner pid lässt den Prozessbaum verwaist zurück. Der Launcher läuft in einer eigenen Session, und genau das macht den Baum identifizierbar — killpg erreicht runqmc und mpirun, und die Session-ID findet die Ränge, die mpirun in eigene Prozessgruppen gesetzt hat — sein Exit-Code übersteht einen Neustart des MCP-Servers, und die Ausgabe von runqmc landet in einem Log statt im JSON-RPC-Stream. Eine recycelte pid kann nicht als lebender Job durchgehen: Die Startzeit von /proc/<pid> wird verglichen, und ein Zombie zählt nicht als laufend.

Der out-Parser

parse_out ist eine einfache Funktion ohne MCP und ohne Abhängigkeiten. Eine out-Datei ist eine Abfolge von Phasen, nicht ein einzelnes Ergebnis — vmc_opt schreibt pro Zyklus eine VMC- und eine OPTIMIZATION-Phase, vmc_dmc schreibt VMC, DMC-Equilibrierung und DMC-Statistikakkumulation — sie gibt also phases zurück, und result zeigt auf die letzte Phase, die eine Energie enthält.

from casino_mcp.parse_out import parse_out

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

Die einzige darin abgeleitete Zahl ist der Stichprobenvarianzfehler eines Ein-Block-Laufs, den CASINO nicht ausgibt; er wird aus dem einen Block genau so übernommen, wie envmc es tut, und als derived gekennzeichnet. Nichts ruft zur Laufzeit envmc oder endmc in einer Shell auf — endmc parst Zahlen unter einem Nicht-C-Locale falsch.

Tests

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

Die Unit-Test-Suite läuft überall: Der Parser wird Feld für Feld gegen fünf echte out-Dateien unter tests/data/ geprüft — jeweils mit dem input, das sie erzeugt hat — sowie anhand aller achtzehn Berechnungen unter examples/, während der Launcher, die Prozessgruppe und die Schutzmechanismen gegen ein gefälschtes runqmc-Shellskript getestet werden.

pytest -m integration

Die Integrationssuite benötigt ein echtes CASINO, darf aber nichts außerhalb dieses Repositories verwenden. Sie prüft parse_out gegen CASINOs eigenes envmc für jede out-Datei in examples/, führt den gesamten Baum erneut gegen die installierte Binärdatei aus und steuert den Server über echtes stdio MCP, wobei echte VMC-Berechnungen gestartet und gestoppt werden.

examples/ enthält achtzehn Berechnungen, die als Abdeckung der Einstellungen ausgewählt wurden, mit denen CASINO ausgeführt werden kann – jede Runtype-, Basistyp-, Optimierer- und Wellenfunktionsoption kommt mindestens einmal vor, ebenso die zwei Dateien, die ein Parser stillschweigend falsch verarbeitet: eine Ausführung, die nie eine Energie ausgegeben hat, und eine, die zwischen Optimierungszyklen unterbrochen wurde. examples/README.md erklärt, wozu jede einzelne da ist.

Sie sind kurz und mit festen Startwerten versehen, sodass der Baum zugleich als Prüfung für CASINO selbst dient: Führt man ihn bei einer neuen Version erneut aus, wird jede Zeile, die der Parser liest und die umbenannt oder entfernt wurde, benannt, statt stillschweigend zu einem None zu werden. Nur das wird geprüft – verschobene Zahlen werden zur Bewertung durch einen Menschen gemeldet.

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 spricht das JSON-RPC von Hand ohne SDK und gibt jede Zeile in beide Richtungen aus. Lies es, bevor du ein Tool hinzufügst.

Lizenz

MIT.

Available Tools

6 tools
casino_list_jobsC

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

Inputs: limit. Returns: object

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.

Inputs: dest (required), source (required), jastrow, runtype, +3 more. Returns: object

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.

Inputs: job_id (required). Returns: object

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.

Inputs: workdir (required), nproc, resume, unlock, +2 more. Returns: object

casino_statusA

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

Inputs: job_id (required). Returns: object

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.

Inputs: job_id (required), timeout. Returns: object

Tool Schema Changelog

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

Loading tool schema changelog…

    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

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      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
      C
      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
      17 PyPI
      1
      MIT