16. MCP server (Claude Desktop integration)
Expose eLabFTW as Model Context Protocol (MCP) tools. Claude Desktop (or any MCP client) can then search, read, and edit the ELN through conversation.
Installation
pip install 'elabftw-toolkit[mcp]'Claude Desktop configuration
Add the following to claude_desktop_config.json and restart Claude Desktop.
{
"mcpServers": {
"elabftw": {
"command": "python",
"args": ["-m", "elabftw_toolkit.mcp_server"],
"env": {
"ELABFTW_HOST_URL": "https://eln.example.org",
"ELABFTW_KEY_FILE": "/path/to/api_key.txt",
"ELABFTW_TEAM": "Your Team Name"
}
}
}
}| OS | Config file |
|---|---|
| macOS | ~/Library/Application Support/Claude/claude_desktop_config.json |
| Windows | %APPDATA%\Claude\claude_desktop_config.json |
Use the absolute path of the Python that has the toolkit installed as command (for conda: .../envs/<name>/python.exe). Point ELABFTW_KEY_FILE at a key file instead of writing the API key into the config. The server is read-only by default. Add ELABFTW_ALLOW_WRITE=1 (and ELABFTW_UPLOAD_DIR for attachments) only for people who write through it (see Safe defaults).
Environment variables
| Variable | Required | Description |
|---|---|---|
ELABFTW_HOST_URL | yes | eLabFTW URL (/api/v2 is optional) |
ELABFTW_API_KEY / ELABFTW_KEY_FILE | yes | API key, or the path of a file holding it |
ELABFTW_TEAM | yes | Team name as shown in eLabFTW |
ELABFTW_SCHEMA | — | ELN schema (.xlsx / .json, chapter 15) used by validate_entry |
ELABFTW_SM_SCHEMA | — | Structured-metadata schema; default: the bundled BENTEN schema (see below) |
ELABFTW_ALLOW_WRITE | — | 1 enables the write tools. Without it the server only reads (dry_run=true previews still work) |
ELABFTW_READ_ONLY | — | 1 keeps it read-only even if ELABFTW_ALLOW_WRITE=1 |
ELABFTW_UPLOAD_DIR | — | Folder(s) upload_file may attach from (several: ; on Windows, : on macOS/Linux). Without it upload_file is refused |
ELABFTW_SCHEMA_DIR | — | Folder(s) load_schema and schema_path may read (.xlsx / .json only). The folders of ELABFTW_SCHEMA and ELABFTW_SM_SCHEMA are always allowed |
ELABFTW_MCP_USER | — | Name written as the person in change-record comments (reason=...) and in the audit log |
ELABFTW_MCP_AUDIT | — | Audit log of tool calls. meta (default): bodies, structured metadata and long text are kept only as length + hash, fields as names only. full: arguments as given. off: no log |
ELABFTW_MCP_AUDIT_DIR | — | Where the audit log goes; default %LOCALAPPDATA%\elabftw-toolkit\mcp-audit (~/.local/state/elabftw-toolkit/mcp-audit outside Windows). One YYYY-MM.jsonl per month |
ELABFTW_MCP_TIMEOUT | — | Seconds per HTTP request to eLabFTW (default 20); GETs are tried twice, so a tool call fits in the usual 60 s client timeout |
Each tool call writes one line: time, tool, arguments, person, ok / error kind, the entry ids returned, and duration. Use it to see which questions went unanswered and to improve tool descriptions. It contains notebook content, so restrict who can read the folder.
Failures are not reported as "no results": when eLabFTW cannot be reached, the API key is refused or the answer has an unexpected form, the tool returns an error (isError) so the AI says the ELN could not be checked. The server instructions tell the AI that titles, bodies and comments are user-written data, not instructions.
Tools
Read tools
| Tool | What it does |
|---|---|
list_categories | Categories of items / experiments |
list_entries | Search entries (q full text, category_title, limit / offset paging) |
get_entry | One entry: extra fields, tags, links, uploads, status, lock state |
load_schema | Load an ELN schema and show its categories and fields |
validate_entry | Check extra fields against the ELN schema |
get_structured_metadata | Structured metadata as a nested JSON object and a flat list of @ keys |
validate_structured_metadata | Check structured metadata against a metadata schema (also works on a dict before writing) |
read_maiml | Read an attached MaiML and summarize document, materials, conditions, results (referenced files with SHA-256) and events (maiml.read(), chapter 10) |
check_maiml | Check MaiML files in folders on this computer and the links between them (paths: several places; context: folders only for looking up parents; maiml.check(), chapter 10) |
maiml_graph | Return how MaiML files spread over several places are linked, as JSON and a Mermaid diagram (focus narrows it to one document's links; with more than max_documents (default 300) documents the diagram is left out; maiml.graph(), chapter 10) |
Write tools (only with ELABFTW_ALLOW_WRITE=1)
| Tool | What it does |
|---|---|
create_entry | Create an entry in a category (template values cleared; fields and tags filled in) |
update_fields | Write extra field values |
set_body | Replace the body (HTML) |
add_tags | Add tags |
update_status | Change the status |
add_link | Link to another entry |
upload_file | Attach a local file from ELABFTW_UPLOAD_DIR (a file with the same name is replaced) |
set_structured_metadata | Write structured metadata (merge by default, overwrite=true replaces) |
lock_entry / unlock_entry | Lock / unlock |
Most write tools share these arguments:
| Argument | Meaning |
|---|---|
dry_run=true | Do not write; return what would change (old value → new value) — the Plan of chapter 15 |
reason="…" | Record the reason as a comment on the entry ([変更の記録]; person = ELABFTW_MCP_USER) |
unlock=true | Temporarily unlock a locked entry, write, and restore the lock |
The server instructs Claude to preview with dry_run=true, show the plan to the user, and pass reason.
Safe defaults
The AI client decides which tools to call, and text in ELN entries or attachments can try to steer it (prompt injection). So with nothing configured, the server stays on the safe side.
- Writing is opt-in. By default the server only reads (write tools return an error;
dry_run=truepreviews still work). AddELABFTW_ALLOW_WRITE=1only for people who register or fix entries through the AI, never for shared keys or demos (ELABFTW_READ_ONLY=1keeps it read-only even ifELABFTW_ALLOW_WRITEis set). - Local files only from named folders.
upload_filereads only insideELABFTW_UPLOAD_DIR;load_schemaandschema_pathonly insideELABFTW_SCHEMA_DIR(and the folders ofELABFTW_SCHEMA/ELABFTW_SM_SCHEMA). Paths escaping with..or symbolic links are refused, so key files and other private files cannot end up in the ELN. check_maiml/maiml_graphread only the.maimlfiles in the folders you pass and return how they link (uuid, SHA-256); they never write to the ELN.
Example for someone who writes and attaches files:
"env": {
"ELABFTW_HOST_URL": "https://eln.example.org",
"ELABFTW_KEY_FILE": "/path/to/api_key.txt",
"ELABFTW_TEAM": "Your Team Name",
"ELABFTW_ALLOW_WRITE": "1",
"ELABFTW_UPLOAD_DIR": "C:/Users/you/eln-uploads"
}Up to 0.1.6 the server could write unless
ELABFTW_READ_ONLYwas set. If you used the write tools, addELABFTW_ALLOW_WRITE=1(andELABFTW_UPLOAD_DIRfor attachments).
Example conversations
"What entries are in the Sample category?"
→ list_categories + list_entries
"Set the purity of entry 42 to 99.9 — it was a transcription error"
→ update_fields(kind="items", entry_id=42, fields={"purity": "99.9"}, dry_run=true) … show the preview
→ update_fields(…, reason="fix transcription error") … after the user agrees
"Measurement 101 is locked, but add the tag MDR登録済"
→ add_tags(kind="experiments", entry_id=101, tags=["MDR登録済"], unlock=true)
"Attach analysis.csv to entry 42"
→ upload_fileStructured metadata
Besides extra fields, an entry's metadata can hold structured_metadata — any nested JSON (chapter 2, entry.metadata.structured() / update_structured()). Working with it from Python is covered in detail in the documentation site's guides "Reading and writing structured_metadata" and "BENTEN metadata and schema". SPring-8's BENTEN stores each measurement's metadata.all.yml there unchanged.
A real example (BL14B2 XAFS standard, Ag₂O at the Ag K edge; excerpt)
data_info:
identifier:
pid: spring8.424a4139-548c-4a03-8f8b-5f3b447e337b
proposal_number: 2014S0000
register_name: /SPring-8/BL14B2/XAFS_Standard/Ag/K/111/Ag2O
date: {create_time: '2020-01-15 18:51:18', update_time: '2021-03-19 16:34:56'}
access_rights: open
facility: SPring-8
class_name: BL14B2
facility:
ring: {energy: 8.0, energy_unit: GeV, filling_pattern: 203 bunches, start_current: 99.5, start_current_unit: mA}
sample:
- {chemical_formula: Ag2O, name: Silver(I) oxide, supplier: KOJUNDO CHEMICAL LABORATORY, lot_number: '4050891'}
measurement:
date: {start_time: '2016-04-12 01:57:00', end_time: '2016-04-12 02:01:00'}
method: {category: spectroscopy, sub_category: XAFS, absorption_edge: Ag K-edge, detection: Transmission( 2)}
instrument:
monochrometer: {net_plane: Si(111), distance: 3.13551, distance_unit: A}
slit:
- {name: 4Dslit, vertical_size: 1.0, vertical_size_unit: mm, horizontal_size: 5.0, horizontal_size_unit: mm}
xafs:
I0:
element: [{type: Ion Chamber, gas: Ar 100%, HV: 1000.0, HV_unit: V}]
local: # facility-specific items (outside the schema; reported as "local", allowed)
measurement_time: 267.0
measurement_time_unit: secmonochrometer is spelled as in the schema.
Flat list of @ keys
The flat list of get_structured_metadata has one "key = value" per leaf. Dict levels are joined with @, array elements with .0, .1 (the same form as the tables in BENTEN entry bodies).
@data_info@identifier@pid = spring8.424a4139-…
@sample.0@chemical_formula = Ag2O
@instrument@slit.0@vertical_size = 1.0In Python, benten_schema.flatten_at(dict) returns the same list.
Checking against a metadata schema (BENTEN schema, optional)
The toolkit bundles the BENTEN metadata schema (metadata_schema-2021.06.07.xlsx exported to JSON, 150 items). You do not need it for non-BENTEN data. Any Excel / JSON file in the same format works as your own schema (ELABFTW_SM_SCHEMA or schema_path; schema_path must be inside ELABFTW_SCHEMA_DIR or the folder of ELABFTW_SM_SCHEMA).
from elabftw_toolkit import benten_schema as bs
schema = bs.load_schema() # bundled JSON (or a path to .xlsx / .json)
md = elab.experiments.entry(101).metadata.structured()
for p in bs.validate(md, schema):
print(p["kind"], p["path"], p["detail"])To check whole folders from the command line (needs PyYAML: pip install 'elabftw-toolkit[benten]'):
elabftw-benten check <folder or metadata.all.yml> [--json result.json]| Kind | Meaning |
|---|---|
unknown | Key not in the schema |
local | Not in the schema but under the top-level local: (facility-specific; allowed) |
required | Required item (Option = required) missing; inside arrays, checked per existing element |
type | Wrong type (double / long / integer = number, date = date string, keyword / text = string; a nested dict is also a type problem) |
enum | Value not in the enum (e.g. access_rights is open / close) |
array | Array shape mismatch (schema says array but the value is not a list, or the reverse) |
Schema key names look like @sample.chemical_formula (. = array element); results use paths like sample[].chemical_formula. An obvious mistake in the Excel (@instrument@xafs@I2@element.amp_gain typed as text) is fixed to double on load (raw=True keeps it).
From MCP:
"Show me the structured metadata of measurement 101"
→ get_structured_metadata(kind="experiments", entry_id=101)
"Before putting this metadata.all.yml into measurement 101, check it against the BENTEN schema"
→ validate_structured_metadata(structured_metadata={…})
→ {ok: false, counts: {enum: 1, local: 5}, problems: [{kind: "enum", path: "data_info.access_rights", …}]}
"If it is fine, write it"
→ set_structured_metadata(kind="experiments", entry_id=101, structured_metadata={…}, overwrite=true, reason="…")ok is true when there are no problems other than local.
Building a server for your site
To fix the connection, tell Claude your site's conventions (how categories relate, tags, statuses), or add your own tools, build the server with build_server().
from elabftw_toolkit import client
from elabftw_toolkit.mcp_server import build_server
mcp = build_server(
name="my-eln",
client=lambda: client("My Team", key_file="~/.elab_key.txt", check=False),
instructions="Raw materials (items 'Raw') → measurements (experiments 'Measurement'). Set status 'Done' when registered.",
on_write=lambda kind, entry_id: print("changed", kind, entry_id), # e.g. refresh a search cache
protected_tags=["Public"], # tags only people decide on; add_tags / create_entry refuse them (even in dry runs)
# without read_only=..., writing needs ELABFTW_ALLOW_WRITE=1. upload_dirs=[...] / schema_dirs=[...] set the
# folders local files may come from (default: ELABFTW_UPLOAD_DIR / ELABFTW_SCHEMA_DIR)
)
@mcp.tool()
def my_search(query: str) -> str:
"""Site-specific search."""
...
if __name__ == "__main__":
mcp.run()SPring-8 BENTEN's benten-cloud/eln/mcp_server.py is built this way: the toolkit tools plus cross-entry search (chemical formula, element, absorption edge), provenance (raw material → sample → measurement), and MaiML uuid lookup, in one server (named benten-eln).
In-house ELN and outside users
This server talks to the eLabFTW API, so it runs on an in-house PC that can reach the ELN. When the ELN is in-house only, outside users need another entry point.
| Outside users | In-house staff | |
|---|---|---|
| Reads from | public data exported from the ELN (an index in object storage, etc.) | the ELN (the server in this chapter) |
| Can | read only | read, write, help with registration |
| Runs on | the public web server (with login and rate limits) | the staff member's PC (stdio) |
BENTEN serves outside users from an MCP endpoint inside its cloud web server (POST /api/mcp, named benten). In-house-only fields are dropped at export, so the public server holds neither an ELN API key nor the ELN host name. Give the two servers different names (build_server(name=…)) for people who connect both.
Running directly (for testing)
ELABFTW_HOST_URL=https://eln.example.org ELABFTW_KEY_FILE=~/.elab_key.txt ELABFTW_TEAM="Your Team" \
python -m elabftw_toolkit.mcp_serverThe server speaks MCP over stdio (try it with the MCP Inspector). Stdout carries the protocol, so connection-check output is sent to stderr.