labmcp-ms-data 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ dist/
7
+ build/
8
+ *.egg-info/
9
+ .DS_Store
10
+ *.jsonl
11
+ !**/fixtures/*.jsonl
12
+ .idea/
13
+ .vscode/
14
+
15
+ CLAUDE.md
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.5
2
+ Name: labmcp-ms-data
3
+ Version: 0.1.0
4
+ Summary: MCP server for mass-spectrometry data files (mzML, mzMLb, Bruker timsTOF TDF; vendor files via msconvert/ThermoRawFileParser): run info, TIC/BPC, XICs, spectra, MS2 search, QC.
5
+ Project-URL: Homepage, https://github.com/K-Dense-AI/lab-instrument-mcps/tree/main/servers/chemistry/ms-data
6
+ Author: K-Dense and LabMCP contributors
7
+ License-Expression: Apache-2.0
8
+ Keywords: lc-ms,mass-spectrometry,mcp,metabolomics,msconvert,mzml,proteomics,pyteomics,timstof
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: labmcp<0.2,>=0.1
11
+ Requires-Dist: lxml>=4.9
12
+ Requires-Dist: numpy>=1.21
13
+ Requires-Dist: psims>=1.3
14
+ Requires-Dist: pyteomics>=4.7
15
+ Provides-Extra: bruker
16
+ Requires-Dist: timsrust-pyo3<0.5,>=0.4; extra == 'bruker'
17
+ Provides-Extra: mzmlb
18
+ Requires-Dist: h5py>=3.6; extra == 'mzmlb'
19
+ Requires-Dist: hdf5plugin>=4; extra == 'mzmlb'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # Mass Spectrometry Data (mzML, Bruker TDF, vendor conversion) — MCP Server
23
+
24
+ <!-- mcp-name: io.github.K-Dense-AI/labmcp-ms-data -->
25
+
26
+ Let an AI agent find, read and analyse **LC-MS data files from any vendor** through open interfaces: list the runs in a folder, report the instrument and acquisition details, plot TIC/BPC chromatograms, extract ion chromatograms with apex and area, read spectra, find MS2 scans by precursor m/z, and run a quick QC. Vendor files are converted to mzML with a converter **you** have installed. This is a data server: it controls no hardware.
27
+
28
+ | | |
29
+ |---|---|
30
+ | **Package** | `labmcp-ms-data` |
31
+ | **Instruments** | Any LC-MS run saved as mzML / mzML.gz / mzMLb; Bruker timsTOF (`.d`, TDF) read directly; Thermo `.raw`, Waters `.raw` folders, Agilent `.d`, SCIEX `.wiff`/`.wiff2`, Shimadzu `.lcd`, Bruker BAF `.d` after conversion |
32
+ | **Interfaces** | Files (a local or network data folder) |
33
+ | **Protocol** | [mzML 1.1](https://www.psidev.info/mzML) via [pyteomics](https://pyteomics.readthedocs.io/en/latest/api/mzml.html); mzMLb via pyteomics + h5py; Bruker TDF via its SQLite schema + [timsrust](https://github.com/MannLabs/timsrust) ([timsrust-pyo3](https://github.com/jspaezp/timsrust_pyo3)); conversion with [msconvert](https://proteowizard.sourceforge.io/tools/msconvert.html) or [ThermoRawFileParser](https://github.com/compomics/ThermoRawFileParser) |
34
+ | **Status** | 🧪 **simulated**: tested against a synthetic LC-MS run, hand-written and generated mzML/mzMLb files and a small Bruker TDF test set; not yet verified on a wide range of real instrument files. [Report a test](https://github.com/K-Dense-AI/lab-instrument-mcps/issues/new?template=hardware-verification.yml) |
35
+
36
+ ## Try it without data
37
+
38
+ ```bash
39
+ uvx labmcp-ms-data --simulate --check
40
+ ```
41
+
42
+ `--simulate` serves one synthetic 12-minute DDA LC-MS/MS run (`simulated_lcms_run.mzML`): eight known analytes (caffeine, sulfamethoxazole, leucine enkephalin, angiotensin II 2+, verapamil, glu-fibrinopeptide B 2+, reserpine, terfenadine) eluting as Gaussian LC peaks with isotope envelopes, a polysiloxane background ion, chemical noise, a top-5 DDA method with dynamic exclusion and fragment spectra, AGC-like injection times, and one electrospray dropout at ~10.6 min for the QC tool to find.
43
+
44
+ ## Point it at your data
45
+
46
+ 1. **Install** (pick the extras you need):
47
+ ```bash
48
+ uvx labmcp-ms-data --help # mzML / mzML.gz
49
+ uvx --from 'labmcp-ms-data[bruker]' labmcp-ms-data --help # + Bruker timsTOF spectra/XICs
50
+ uvx --from 'labmcp-ms-data[mzmlb]' labmcp-ms-data --help # + mzMLb
51
+ ```
52
+ 2. **Choose the data folder** with `--address` (default: the current directory; the server refuses to start in the filesystem root, where many MCP clients launch servers, without an `--address`). Subfolders are searched. The agent can only read and write inside this folder: paths with `..`, absolute paths elsewhere and symlinks pointing outside are refused.
53
+ ```bash
54
+ uvx labmcp-ms-data --address ~/data/lcms --check
55
+ ```
56
+ 3. **Vendor files (optional):** install a converter yourself; this package never bundles or downloads vendor libraries.
57
+ - **Thermo .raw, any OS:** [ThermoRawFileParser](https://github.com/compomics/ThermoRawFileParser) (`--option converter=thermorawfileparser`, plus `--option converter_path=/opt/trfp/ThermoRawFileParser.dll` if it isn't on PATH; `.dll` is started with `dotnet`, `.exe` with `mono` on Linux/macOS). With `converter=auto`, a `converter_path` is recognised from its file name.
58
+ - **All vendors, Windows:** [ProteoWizard msconvert](https://proteowizard.sourceforge.io/download.html) (`--option converter=msconvert`).
59
+ - **All vendors, Linux/macOS:** Docker and `docker pull proteowizard/pwiz-skyline-i-agree-to-the-vendor-licenses` (`--option converter=docker`). Pulling the image means you accept the vendor licences. Only the input's folder (read-only) and the output folder are mounted into the container. On Apple Silicon it runs under x86-64 emulation (slow). On Linux the output files are owned by root.
60
+ - `converter=auto` (default) tries ThermoRawFileParser for Thermo files, then msconvert, then Docker.
61
+
62
+ The commands used are: `ThermoRawFileParser -i=<file> -o=<dir> -f=2 [-p] [-g]` and `msconvert <file> -o <dir> --mzML --zlib [--gzip] [--filter "peakPicking vendor msLevel=1-"]` (inside Docker via `wine msconvert`). They are run without a shell, with a timeout; on timeout the converter's whole process tree (and the Docker container) is killed and the incomplete output is deleted.
63
+
64
+ ## Add to your MCP client
65
+
66
+ **Claude Code**
67
+ ```bash
68
+ claude mcp add ms-data -- uvx --from 'labmcp-ms-data[bruker]' labmcp-ms-data --address /path/to/data
69
+ ```
70
+
71
+ **Claude Desktop / Cursor / Windsurf** (`claude_desktop_config.json`, `.cursor/mcp.json`, …)
72
+ ```json
73
+ {
74
+ "mcpServers": {
75
+ "ms-data": {
76
+ "command": "uvx",
77
+ "args": ["--from", "labmcp-ms-data[bruker]", "labmcp-ms-data", "--address", "/path/to/data",
78
+ "--option", "converter=docker"]
79
+ }
80
+ }
81
+ }
82
+ ```
83
+
84
+ Add `--read-only` to hide `convert_to_mzml` (the only tool that writes a data file; `save_path` CSV exports inside the data folder remain available). A `save_path` must end in `.csv` (a name without an extension gets one), and an existing file is never replaced unless the call passes `overwrite=true`. For other clients, generate the snippet with `uvx labmcp config ms-data --address /path/to/data --client vscode` (also `cursor`, `codex`, `claude-code`).
85
+
86
+ ## Tools
87
+
88
+ <!-- TOOLS:START -->
89
+ | Tool | Kind | Description |
90
+ |---|---|---|
91
+ | `convert_to_mzml` | 🎛 control | Convert a vendor file (Thermo .raw, Waters .raw, Agilent .d, SCIEX .wiff, Shimadzu .lcd, Bruker .d) to mzML with the converter the user installed (ThermoRawFileParser, ProteoWizard msconvert, or msconvert in Docker; chosen with --option converter=...). Writes a new file in the data folder. Can take minutes; fails with install instructions if no converter is set up. |
92
+ | `extract_ion_chromatogram` | 👁 read | Extracted ion chromatogram (XIC/EIC) for one or more m/z values: the summed intensity within ± tolerance (ppm or Da) in every MS1 spectrum (or another `ms_level`). For each target returns the apex RT and intensity, the apex peak's boundaries, area (intensity x min, no baseline subtraction) and FWHM, plus a downsampled trace. Reads every spectrum in the RT window, so restrict `rt_start_min`/`rt_end_min` on long runs. |
93
+ | `find_ms2_scans` | 👁 read | Find the MS2 (MSn) spectra whose precursor m/z is within ± tolerance of `precursor_mz`, optionally within an RT window and for one charge state. Returns index, scan number, RT, precursor m/z, error in ppm, charge and intensity; open any hit with get_spectrum. |
94
+ | `get_bpc` | 👁 read | Base peak chromatogram (intensity of the most intense peak per spectrum, with its m/z) vs retention time, downsampled to `max_points`. Cleaner than the TIC for spotting eluting compounds; the base-peak m/z tells you which ion dominates each part of the run. |
95
+ | `get_command_log` | 👁 read | Return the most recent raw commands sent to / replies received from the instrument (newest last). Useful for debugging and for recording what was done. |
96
+ | `get_connection_info` | 👁 read | Report which instrument is connected (identity, address, simulated or real), whether the server is read-only, and the active safety limits. Call this first. |
97
+ | `get_run_info` | 👁 read | Describe one run: instrument vendor/model/serial (when the file records them), acquisition date, software, number of spectra per MS level, retention-time and m/z ranges, polarity, centroid/profile, and whether ion-mobility data is present. The first call on a large file indexes it (can take a while); later calls are instant. |
98
+ | `get_spectrum` | 👁 read | Read one spectrum, chosen by `index`, `scan_number`, `native_id` or nearest `rt_min` (give exactly one). Returns MS level, RT, polarity, centroid/profile, precursor m/z and charge for MS2, a summary (peak count, TIC, base peak, m/z range) and the `top_n` most intense peaks; `save_path` writes the full peak list to CSV. For profile spectra the top peaks are local maxima of the profile. |
99
+ | `get_tic` | 👁 read | Total ion chromatogram (sum of all intensities per spectrum vs retention time) for one MS level, downsampled to `max_points` (keeping the maximum in each bin so peaks survive). Returns the apex, median and area; `save_path` writes every point to CSV. |
100
+ | `list_runs` | 👁 read | Find mass-spectrometry runs in the data folder and detect each one's vendor and format (mzML/mzML.gz/mzMLb, Bruker .d TDF or BAF, Agilent .d, Thermo .raw, Waters .raw folder, SCIEX .wiff/.wiff2, Shimadzu .lcd, mzXML). `readable_directly=false` means the run must be converted with convert_to_mzml before it can be analysed. |
101
+ | `reconnect` | 🛑 safety | Close and re-open the connection to the instrument (e.g. after it was power cycled or a cable was re-plugged). |
102
+ | `summarise_run` | 👁 read | Quick QC of a run: MS1/MS2 counts, TIC stability (CV, spray dropouts), where the signal elutes, cycle time, MS2 scans per cycle, median injection times and how often MS2 hit the maximum injection time, and precursor charge states. Returns plain-language warnings. |
103
+ <!-- TOOLS:END -->
104
+
105
+ `get_connection_info`, `get_command_log` and `reconnect` are built into every LabMCP server (`reconnect` here closes the cached runs). There are no HAZARD tools, because nothing physical is controlled, so no SAFETY stop tool is needed.
106
+
107
+ ## Safety limits
108
+
109
+ | Limit | Default | Meaning |
110
+ |---|---|---|
111
+ | `max_conversion_time_s` | 3600 s | Longest time a `convert_to_mzml` call may run before the converter is stopped |
112
+ | `max_xic_targets` | 50 | Most m/z values in one `extract_ion_chromatogram` call |
113
+
114
+ Override at launch: `--limit max_conversion_time_s=7200`.
115
+
116
+ ## Example prompts
117
+
118
+ - "Which runs are in this folder, and which ones need converting?"
119
+ - "Give me the instrument, acquisition date and scan counts for QC_2024_03_01.mzML."
120
+ - "Extract XICs for caffeine (195.0877) and verapamil (455.2904) at 5 ppm and report apex RT and area."
121
+ - "Find every MS2 scan of m/z 523.7745 between 5 and 7 min and show me the fragments of the most intense one."
122
+ - "Run a QC on the last three runs: any spray dropouts, and how many MS2 per cycle?"
123
+ - "Convert sample_07.raw to mzML, then plot its base peak chromatogram."
124
+
125
+ ## Notes
126
+
127
+ - **Format support:** mzML (indexed or not, optionally `.gz`) through pyteomics (Apache-2.0), using the PSI-MS vocabulary bundled with psims (no download). mzMLb needs the `[mzmlb]` extra (h5py, hdf5plugin). Gzipped mzML is decompressed to a temporary file for random access.
128
+ - **Bruker timsTOF (TDF):** run metadata (instrument, serial, date, m/z and 1/K0 ranges), the TIC (`Frames.SummedIntensities`), BPC intensity (`Frames.MaxIntensity`, the most intense single peak in any mobility scan; its m/z is not stored) and the DDA precursor list are read straight from the `analysis.tdf` SQLite tables (`GlobalMetadata`, `Frames`, `Precursors`, `PasefFrameMsMsInfo`), so they work without extras. Spectra and XICs need the `[bruker]` extra (`timsrust-pyo3`, Apache-2.0, wheels for Linux/macOS/Windows). MS1 and diaPASEF frames are summed over ion mobility (diaPASEF MS2 frames mix all isolation windows); each ddaPASEF precursor is one MS2 spectrum. Ion mobility is not resolved in the outputs. Bruker BAF `.d` folders need conversion.
129
+ - **Vendor formats:** Thermo, Waters, Agilent, SCIEX, Shimadzu and Bruker BAF files can only be decoded with the vendors' own libraries, whose licences don't allow redistribution. The server detects them and converts them with a tool you installed (see above). It never downloads vendor code.
130
+ - **Numbers:** retention times are in minutes (mzML scan start times in seconds are converted, going by the unit accession); XIC intensity is the sum of all peaks inside ± tolerance; areas are trapezoidal integrals over RT in minutes, with no baseline subtraction, between the points where the trace falls to 1 % of the apex or reaches a valley. The FWHM is measured within those bounds (it is `null` when a co-eluting peak keeps the trace above half height). Use them for relative comparisons.
131
+ - **Big files:** the first access to a run makes one pass over all spectra to index it (TIC, precursors, RTs). Up to 4 runs stay cached (`--option cache_size=N`). A run is reopened automatically when the file changes (modification time or size). XICs read every spectrum in the RT window, so narrow the window on long runs.
132
+ - **Profile data:** chromatograms and XICs work as-is. `get_spectrum` reports local maxima as "peaks". Convert with peak picking for proper centroids.
133
+
134
+ ## Hardware verification
135
+
136
+ | Instrument / file type | Software version | Interface | Verified by | Date |
137
+ |---|---|---|---|---|
138
+ | *none yet: [be the first](https://github.com/K-Dense-AI/lab-instrument-mcps/issues/new?template=hardware-verification.yml)* | | | | |
@@ -0,0 +1,117 @@
1
+ # Mass Spectrometry Data (mzML, Bruker TDF, vendor conversion) — MCP Server
2
+
3
+ <!-- mcp-name: io.github.K-Dense-AI/labmcp-ms-data -->
4
+
5
+ Let an AI agent find, read and analyse **LC-MS data files from any vendor** through open interfaces: list the runs in a folder, report the instrument and acquisition details, plot TIC/BPC chromatograms, extract ion chromatograms with apex and area, read spectra, find MS2 scans by precursor m/z, and run a quick QC. Vendor files are converted to mzML with a converter **you** have installed. This is a data server: it controls no hardware.
6
+
7
+ | | |
8
+ |---|---|
9
+ | **Package** | `labmcp-ms-data` |
10
+ | **Instruments** | Any LC-MS run saved as mzML / mzML.gz / mzMLb; Bruker timsTOF (`.d`, TDF) read directly; Thermo `.raw`, Waters `.raw` folders, Agilent `.d`, SCIEX `.wiff`/`.wiff2`, Shimadzu `.lcd`, Bruker BAF `.d` after conversion |
11
+ | **Interfaces** | Files (a local or network data folder) |
12
+ | **Protocol** | [mzML 1.1](https://www.psidev.info/mzML) via [pyteomics](https://pyteomics.readthedocs.io/en/latest/api/mzml.html); mzMLb via pyteomics + h5py; Bruker TDF via its SQLite schema + [timsrust](https://github.com/MannLabs/timsrust) ([timsrust-pyo3](https://github.com/jspaezp/timsrust_pyo3)); conversion with [msconvert](https://proteowizard.sourceforge.io/tools/msconvert.html) or [ThermoRawFileParser](https://github.com/compomics/ThermoRawFileParser) |
13
+ | **Status** | 🧪 **simulated**: tested against a synthetic LC-MS run, hand-written and generated mzML/mzMLb files and a small Bruker TDF test set; not yet verified on a wide range of real instrument files. [Report a test](https://github.com/K-Dense-AI/lab-instrument-mcps/issues/new?template=hardware-verification.yml) |
14
+
15
+ ## Try it without data
16
+
17
+ ```bash
18
+ uvx labmcp-ms-data --simulate --check
19
+ ```
20
+
21
+ `--simulate` serves one synthetic 12-minute DDA LC-MS/MS run (`simulated_lcms_run.mzML`): eight known analytes (caffeine, sulfamethoxazole, leucine enkephalin, angiotensin II 2+, verapamil, glu-fibrinopeptide B 2+, reserpine, terfenadine) eluting as Gaussian LC peaks with isotope envelopes, a polysiloxane background ion, chemical noise, a top-5 DDA method with dynamic exclusion and fragment spectra, AGC-like injection times, and one electrospray dropout at ~10.6 min for the QC tool to find.
22
+
23
+ ## Point it at your data
24
+
25
+ 1. **Install** (pick the extras you need):
26
+ ```bash
27
+ uvx labmcp-ms-data --help # mzML / mzML.gz
28
+ uvx --from 'labmcp-ms-data[bruker]' labmcp-ms-data --help # + Bruker timsTOF spectra/XICs
29
+ uvx --from 'labmcp-ms-data[mzmlb]' labmcp-ms-data --help # + mzMLb
30
+ ```
31
+ 2. **Choose the data folder** with `--address` (default: the current directory; the server refuses to start in the filesystem root, where many MCP clients launch servers, without an `--address`). Subfolders are searched. The agent can only read and write inside this folder: paths with `..`, absolute paths elsewhere and symlinks pointing outside are refused.
32
+ ```bash
33
+ uvx labmcp-ms-data --address ~/data/lcms --check
34
+ ```
35
+ 3. **Vendor files (optional):** install a converter yourself; this package never bundles or downloads vendor libraries.
36
+ - **Thermo .raw, any OS:** [ThermoRawFileParser](https://github.com/compomics/ThermoRawFileParser) (`--option converter=thermorawfileparser`, plus `--option converter_path=/opt/trfp/ThermoRawFileParser.dll` if it isn't on PATH; `.dll` is started with `dotnet`, `.exe` with `mono` on Linux/macOS). With `converter=auto`, a `converter_path` is recognised from its file name.
37
+ - **All vendors, Windows:** [ProteoWizard msconvert](https://proteowizard.sourceforge.io/download.html) (`--option converter=msconvert`).
38
+ - **All vendors, Linux/macOS:** Docker and `docker pull proteowizard/pwiz-skyline-i-agree-to-the-vendor-licenses` (`--option converter=docker`). Pulling the image means you accept the vendor licences. Only the input's folder (read-only) and the output folder are mounted into the container. On Apple Silicon it runs under x86-64 emulation (slow). On Linux the output files are owned by root.
39
+ - `converter=auto` (default) tries ThermoRawFileParser for Thermo files, then msconvert, then Docker.
40
+
41
+ The commands used are: `ThermoRawFileParser -i=<file> -o=<dir> -f=2 [-p] [-g]` and `msconvert <file> -o <dir> --mzML --zlib [--gzip] [--filter "peakPicking vendor msLevel=1-"]` (inside Docker via `wine msconvert`). They are run without a shell, with a timeout; on timeout the converter's whole process tree (and the Docker container) is killed and the incomplete output is deleted.
42
+
43
+ ## Add to your MCP client
44
+
45
+ **Claude Code**
46
+ ```bash
47
+ claude mcp add ms-data -- uvx --from 'labmcp-ms-data[bruker]' labmcp-ms-data --address /path/to/data
48
+ ```
49
+
50
+ **Claude Desktop / Cursor / Windsurf** (`claude_desktop_config.json`, `.cursor/mcp.json`, …)
51
+ ```json
52
+ {
53
+ "mcpServers": {
54
+ "ms-data": {
55
+ "command": "uvx",
56
+ "args": ["--from", "labmcp-ms-data[bruker]", "labmcp-ms-data", "--address", "/path/to/data",
57
+ "--option", "converter=docker"]
58
+ }
59
+ }
60
+ }
61
+ ```
62
+
63
+ Add `--read-only` to hide `convert_to_mzml` (the only tool that writes a data file; `save_path` CSV exports inside the data folder remain available). A `save_path` must end in `.csv` (a name without an extension gets one), and an existing file is never replaced unless the call passes `overwrite=true`. For other clients, generate the snippet with `uvx labmcp config ms-data --address /path/to/data --client vscode` (also `cursor`, `codex`, `claude-code`).
64
+
65
+ ## Tools
66
+
67
+ <!-- TOOLS:START -->
68
+ | Tool | Kind | Description |
69
+ |---|---|---|
70
+ | `convert_to_mzml` | 🎛 control | Convert a vendor file (Thermo .raw, Waters .raw, Agilent .d, SCIEX .wiff, Shimadzu .lcd, Bruker .d) to mzML with the converter the user installed (ThermoRawFileParser, ProteoWizard msconvert, or msconvert in Docker; chosen with --option converter=...). Writes a new file in the data folder. Can take minutes; fails with install instructions if no converter is set up. |
71
+ | `extract_ion_chromatogram` | 👁 read | Extracted ion chromatogram (XIC/EIC) for one or more m/z values: the summed intensity within ± tolerance (ppm or Da) in every MS1 spectrum (or another `ms_level`). For each target returns the apex RT and intensity, the apex peak's boundaries, area (intensity x min, no baseline subtraction) and FWHM, plus a downsampled trace. Reads every spectrum in the RT window, so restrict `rt_start_min`/`rt_end_min` on long runs. |
72
+ | `find_ms2_scans` | 👁 read | Find the MS2 (MSn) spectra whose precursor m/z is within ± tolerance of `precursor_mz`, optionally within an RT window and for one charge state. Returns index, scan number, RT, precursor m/z, error in ppm, charge and intensity; open any hit with get_spectrum. |
73
+ | `get_bpc` | 👁 read | Base peak chromatogram (intensity of the most intense peak per spectrum, with its m/z) vs retention time, downsampled to `max_points`. Cleaner than the TIC for spotting eluting compounds; the base-peak m/z tells you which ion dominates each part of the run. |
74
+ | `get_command_log` | 👁 read | Return the most recent raw commands sent to / replies received from the instrument (newest last). Useful for debugging and for recording what was done. |
75
+ | `get_connection_info` | 👁 read | Report which instrument is connected (identity, address, simulated or real), whether the server is read-only, and the active safety limits. Call this first. |
76
+ | `get_run_info` | 👁 read | Describe one run: instrument vendor/model/serial (when the file records them), acquisition date, software, number of spectra per MS level, retention-time and m/z ranges, polarity, centroid/profile, and whether ion-mobility data is present. The first call on a large file indexes it (can take a while); later calls are instant. |
77
+ | `get_spectrum` | 👁 read | Read one spectrum, chosen by `index`, `scan_number`, `native_id` or nearest `rt_min` (give exactly one). Returns MS level, RT, polarity, centroid/profile, precursor m/z and charge for MS2, a summary (peak count, TIC, base peak, m/z range) and the `top_n` most intense peaks; `save_path` writes the full peak list to CSV. For profile spectra the top peaks are local maxima of the profile. |
78
+ | `get_tic` | 👁 read | Total ion chromatogram (sum of all intensities per spectrum vs retention time) for one MS level, downsampled to `max_points` (keeping the maximum in each bin so peaks survive). Returns the apex, median and area; `save_path` writes every point to CSV. |
79
+ | `list_runs` | 👁 read | Find mass-spectrometry runs in the data folder and detect each one's vendor and format (mzML/mzML.gz/mzMLb, Bruker .d TDF or BAF, Agilent .d, Thermo .raw, Waters .raw folder, SCIEX .wiff/.wiff2, Shimadzu .lcd, mzXML). `readable_directly=false` means the run must be converted with convert_to_mzml before it can be analysed. |
80
+ | `reconnect` | 🛑 safety | Close and re-open the connection to the instrument (e.g. after it was power cycled or a cable was re-plugged). |
81
+ | `summarise_run` | 👁 read | Quick QC of a run: MS1/MS2 counts, TIC stability (CV, spray dropouts), where the signal elutes, cycle time, MS2 scans per cycle, median injection times and how often MS2 hit the maximum injection time, and precursor charge states. Returns plain-language warnings. |
82
+ <!-- TOOLS:END -->
83
+
84
+ `get_connection_info`, `get_command_log` and `reconnect` are built into every LabMCP server (`reconnect` here closes the cached runs). There are no HAZARD tools, because nothing physical is controlled, so no SAFETY stop tool is needed.
85
+
86
+ ## Safety limits
87
+
88
+ | Limit | Default | Meaning |
89
+ |---|---|---|
90
+ | `max_conversion_time_s` | 3600 s | Longest time a `convert_to_mzml` call may run before the converter is stopped |
91
+ | `max_xic_targets` | 50 | Most m/z values in one `extract_ion_chromatogram` call |
92
+
93
+ Override at launch: `--limit max_conversion_time_s=7200`.
94
+
95
+ ## Example prompts
96
+
97
+ - "Which runs are in this folder, and which ones need converting?"
98
+ - "Give me the instrument, acquisition date and scan counts for QC_2024_03_01.mzML."
99
+ - "Extract XICs for caffeine (195.0877) and verapamil (455.2904) at 5 ppm and report apex RT and area."
100
+ - "Find every MS2 scan of m/z 523.7745 between 5 and 7 min and show me the fragments of the most intense one."
101
+ - "Run a QC on the last three runs: any spray dropouts, and how many MS2 per cycle?"
102
+ - "Convert sample_07.raw to mzML, then plot its base peak chromatogram."
103
+
104
+ ## Notes
105
+
106
+ - **Format support:** mzML (indexed or not, optionally `.gz`) through pyteomics (Apache-2.0), using the PSI-MS vocabulary bundled with psims (no download). mzMLb needs the `[mzmlb]` extra (h5py, hdf5plugin). Gzipped mzML is decompressed to a temporary file for random access.
107
+ - **Bruker timsTOF (TDF):** run metadata (instrument, serial, date, m/z and 1/K0 ranges), the TIC (`Frames.SummedIntensities`), BPC intensity (`Frames.MaxIntensity`, the most intense single peak in any mobility scan; its m/z is not stored) and the DDA precursor list are read straight from the `analysis.tdf` SQLite tables (`GlobalMetadata`, `Frames`, `Precursors`, `PasefFrameMsMsInfo`), so they work without extras. Spectra and XICs need the `[bruker]` extra (`timsrust-pyo3`, Apache-2.0, wheels for Linux/macOS/Windows). MS1 and diaPASEF frames are summed over ion mobility (diaPASEF MS2 frames mix all isolation windows); each ddaPASEF precursor is one MS2 spectrum. Ion mobility is not resolved in the outputs. Bruker BAF `.d` folders need conversion.
108
+ - **Vendor formats:** Thermo, Waters, Agilent, SCIEX, Shimadzu and Bruker BAF files can only be decoded with the vendors' own libraries, whose licences don't allow redistribution. The server detects them and converts them with a tool you installed (see above). It never downloads vendor code.
109
+ - **Numbers:** retention times are in minutes (mzML scan start times in seconds are converted, going by the unit accession); XIC intensity is the sum of all peaks inside ± tolerance; areas are trapezoidal integrals over RT in minutes, with no baseline subtraction, between the points where the trace falls to 1 % of the apex or reaches a valley. The FWHM is measured within those bounds (it is `null` when a co-eluting peak keeps the trace above half height). Use them for relative comparisons.
110
+ - **Big files:** the first access to a run makes one pass over all spectra to index it (TIC, precursors, RTs). Up to 4 runs stay cached (`--option cache_size=N`). A run is reopened automatically when the file changes (modification time or size). XICs read every spectrum in the RT window, so narrow the window on long runs.
111
+ - **Profile data:** chromatograms and XICs work as-is. `get_spectrum` reports local maxima as "peaks". Convert with peak picking for proper centroids.
112
+
113
+ ## Hardware verification
114
+
115
+ | Instrument / file type | Software version | Interface | Verified by | Date |
116
+ |---|---|---|---|---|
117
+ | *none yet: [be the first](https://github.com/K-Dense-AI/lab-instrument-mcps/issues/new?template=hardware-verification.yml)* | | | | |
@@ -0,0 +1,47 @@
1
+ [project]
2
+ name = "labmcp-ms-data"
3
+ version = "0.1.0"
4
+ description = "MCP server for mass-spectrometry data files (mzML, mzMLb, Bruker timsTOF TDF; vendor files via msconvert/ThermoRawFileParser): run info, TIC/BPC, XICs, spectra, MS2 search, QC."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ requires-python = ">=3.10"
8
+ authors = [{ name = "K-Dense and LabMCP contributors" }]
9
+ keywords = ["mcp", "mass-spectrometry", "lc-ms", "mzml", "proteomics", "metabolomics", "pyteomics", "timstof", "msconvert"]
10
+ dependencies = [
11
+ "labmcp>=0.1,<0.2",
12
+ "numpy>=1.21",
13
+ "pyteomics>=4.7",
14
+ "lxml>=4.9",
15
+ "psims>=1.3",
16
+ ]
17
+
18
+ [project.optional-dependencies]
19
+ bruker = ["timsrust-pyo3>=0.4,<0.5"]
20
+ mzmlb = ["h5py>=3.6", "hdf5plugin>=4"]
21
+
22
+ [dependency-groups]
23
+ dev = ["timsrust-pyo3>=0.4,<0.5", "h5py>=3.6"]
24
+
25
+ [project.scripts]
26
+ labmcp-ms-data = "labmcp_ms_data.server:main"
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/K-Dense-AI/lab-instrument-mcps/tree/main/servers/chemistry/ms-data"
30
+
31
+ [tool.labmcp]
32
+ name = "Mass Spectrometry Data (mzML, Bruker TDF, vendor conversion)"
33
+ domain = "chemistry"
34
+ category = "Mass spectrometry"
35
+ vendor = "Vendor-neutral"
36
+ models = ["Any LC-MS run in mzML/mzMLb", "Bruker timsTOF (TDF .d)", "Thermo .raw, Waters .raw, Agilent .d, SCIEX .wiff/.wiff2, Shimadzu .lcd, Bruker BAF (via conversion)"]
37
+ interfaces = ["File"]
38
+ protocol = "mzML / mzMLb (pyteomics) / Bruker TDF (SQLite + timsrust) / msconvert & ThermoRawFileParser"
39
+ summary = "Read and analyse LC-MS data from any vendor via open formats: find runs, run metadata, TIC/BPC, XICs with apex and area, spectra, MS2 search by precursor, quick QC, and conversion of vendor files with the user's own msconvert or ThermoRawFileParser."
40
+ status = "simulated"
41
+
42
+ [build-system]
43
+ requires = ["hatchling"]
44
+ build-backend = "hatchling.build"
45
+
46
+ [tool.hatch.build.targets.wheel]
47
+ packages = ["src/labmcp_ms_data"]
@@ -0,0 +1,46 @@
1
+ {
2
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
+ "name": "io.github.K-Dense-AI/labmcp-ms-data",
4
+ "title": "Mass Spectrometry Data (mzML, Bruker TDF, vendor conversion)",
5
+ "description": "MCP server for mass-spectrometry data files (mzML, mzMLb, Bruker timsTOF TDF; vendor files via mscon",
6
+ "version": "0.1.0",
7
+ "repository": {
8
+ "url": "https://github.com/K-Dense-AI/lab-instrument-mcps",
9
+ "source": "github",
10
+ "subfolder": "servers/chemistry/ms-data"
11
+ },
12
+ "websiteUrl": "https://github.com/K-Dense-AI/lab-instrument-mcps/tree/main/servers/chemistry/ms-data",
13
+ "packages": [
14
+ {
15
+ "registryType": "pypi",
16
+ "registryBaseUrl": "https://pypi.org",
17
+ "identifier": "labmcp-ms-data",
18
+ "version": "0.1.0",
19
+ "transport": {
20
+ "type": "stdio"
21
+ },
22
+ "environmentVariables": [
23
+ {
24
+ "name": "LABMCP_ADDRESS",
25
+ "description": "Instrument address, e.g. serial:///dev/ttyUSB0 or tcp://192.168.1.50:5025",
26
+ "isRequired": false
27
+ },
28
+ {
29
+ "name": "LABMCP_SIMULATE",
30
+ "description": "Set to 1 to use the built-in simulator (no hardware)",
31
+ "isRequired": false
32
+ },
33
+ {
34
+ "name": "LABMCP_READ_ONLY",
35
+ "description": "Set to 1 to disable all state-changing tools",
36
+ "isRequired": false
37
+ },
38
+ {
39
+ "name": "LABMCP_LIMITS",
40
+ "description": "Safety limit overrides, e.g. max_temperature_c=80",
41
+ "isRequired": false
42
+ }
43
+ ]
44
+ }
45
+ ]
46
+ }
@@ -0,0 +1 @@
1
+ """LabMCP server for Mass Spectrometry Data (mzML, Bruker TDF, vendor conversion)."""
@@ -0,0 +1,148 @@
1
+ """Numerical helpers: chromatogram downsampling, XIC peak integration, spectrum peak lists (numpy only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+
11
+ PROTON_MASS = 1.007276
12
+
13
+
14
+ def downsample_max_indices(y: np.ndarray, max_points: int) -> np.ndarray:
15
+ """Indices kept by :func:`downsample_max` (the highest point of each of ``max_points`` bins)."""
16
+ y = np.asarray(y, dtype=float)
17
+ if y.size <= max_points:
18
+ return np.arange(y.size)
19
+ bins = np.array_split(np.arange(y.size), max_points)
20
+ return np.array([b[int(np.argmax(y[b]))] for b in bins if b.size], dtype=np.int64)
21
+
22
+
23
+ def downsample_max(x: np.ndarray, y: np.ndarray, max_points: int) -> tuple[list[float], list[float]]:
24
+ """Split into ``max_points`` contiguous bins and keep, per bin, the point with the highest ``y``.
25
+
26
+ Keeping the maximum (not the mean) preserves chromatographic peak heights and apex positions.
27
+ """
28
+ x = np.asarray(x, dtype=float)
29
+ y = np.asarray(y, dtype=float)
30
+ idx = downsample_max_indices(y, max_points)
31
+ return x[idx].tolist(), y[idx].tolist()
32
+
33
+
34
+ def trapezoid(y: np.ndarray, x: np.ndarray) -> float:
35
+ y = np.asarray(y, dtype=float)
36
+ x = np.asarray(x, dtype=float)
37
+ if y.size < 2:
38
+ return 0.0
39
+ return float(np.sum((y[1:] + y[:-1]) * np.diff(x)) / 2.0)
40
+
41
+
42
+ @dataclass
43
+ class ChromPeak:
44
+ apex_rt_min: float
45
+ apex_intensity: float
46
+ start_rt_min: float
47
+ end_rt_min: float
48
+ area: float # intensity x minutes, baseline not subtracted
49
+ fwhm_s: float | None
50
+ points_across_peak: int
51
+
52
+
53
+ def _half_crossing(
54
+ x: np.ndarray, y: np.ndarray, i: int, level: float, step: int, lo: int, hi: int
55
+ ) -> float | None:
56
+ """RT where the trace first falls below ``level`` walking from ``i``, within ``lo..hi`` only."""
57
+ j = i
58
+ while lo <= j + step <= hi:
59
+ k = j + step
60
+ if y[k] < level:
61
+ frac = (y[j] - level) / (y[j] - y[k]) if y[j] != y[k] else 0.0
62
+ return float(x[j] + frac * (x[k] - x[j]))
63
+ j = k
64
+ return None
65
+
66
+
67
+ def integrate_apex_peak(
68
+ rt_min: np.ndarray, y: np.ndarray, *, stop_fraction: float = 0.01
69
+ ) -> ChromPeak | None:
70
+ """Find the most intense point and integrate the peak around it.
71
+
72
+ The peak extends from the apex on each side until the trace falls below ``stop_fraction`` (1 %) of the
73
+ apex or reaches a valley (a point lower than the next 2 points on that side). Area is the
74
+ trapezoidal integral of intensity over retention time in minutes, without baseline subtraction.
75
+ """
76
+ rt = np.asarray(rt_min, dtype=float)
77
+ y = np.asarray(y, dtype=float)
78
+ if y.size == 0 or not np.any(y > 0):
79
+ return None
80
+ i = int(np.argmax(y))
81
+ apex = float(y[i])
82
+ stop = stop_fraction * apex
83
+
84
+ def walk(step: int) -> int:
85
+ j = i
86
+ while 0 <= j + step < y.size:
87
+ k = j + step
88
+ if y[k] <= stop:
89
+ return k
90
+ k2 = k + step
91
+ k3 = k2 + step
92
+ if 0 <= k3 < y.size and y[k2] > y[k] and y[k3] > y[k]:
93
+ return k # valley
94
+ j = k
95
+ return j
96
+
97
+ lo, hi = walk(-1), walk(+1)
98
+ # FWHM of the apex peak only: a co-eluting neighbour beyond a valley must not widen it.
99
+ left = _half_crossing(rt, y, i, apex / 2, -1, lo, hi)
100
+ right = _half_crossing(rt, y, i, apex / 2, +1, lo, hi)
101
+ fwhm = (right - left) * 60.0 if left is not None and right is not None else None
102
+ return ChromPeak(
103
+ apex_rt_min=float(rt[i]),
104
+ apex_intensity=apex,
105
+ start_rt_min=float(rt[lo]),
106
+ end_rt_min=float(rt[hi]),
107
+ area=trapezoid(y[lo : hi + 1], rt[lo : hi + 1]),
108
+ fwhm_s=fwhm,
109
+ points_across_peak=int(hi - lo + 1),
110
+ )
111
+
112
+
113
+ def tolerance_da(mz: float, tol: float, unit: str) -> float:
114
+ return mz * tol * 1e-6 if unit == "ppm" else tol
115
+
116
+
117
+ def local_maxima(mz: np.ndarray, intensity: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
118
+ """Crude centroiding of profile data: keep points higher than both neighbours."""
119
+ if intensity.size < 3:
120
+ return mz, intensity
121
+ y = intensity
122
+ keep = np.zeros(y.size, dtype=bool)
123
+ keep[1:-1] = (y[1:-1] > y[:-2]) & (y[1:-1] >= y[2:])
124
+ keep[0] = y[0] > y[1]
125
+ keep[-1] = y[-1] > y[-2]
126
+ return mz[keep], y[keep]
127
+
128
+
129
+ def write_csv(path: Path, header: list[str], columns: list[np.ndarray | list], *, overwrite: bool = False) -> str:
130
+ """Write equal-length columns to CSV and return the absolute path.
131
+
132
+ Without ``overwrite`` the file is created exclusively (``FileExistsError`` if it appeared meanwhile).
133
+ """
134
+ path.parent.mkdir(parents=True, exist_ok=True)
135
+ with path.open("w" if overwrite else "x", newline="", encoding="utf-8") as fh:
136
+ writer = csv.writer(fh)
137
+ writer.writerow(header)
138
+ for row in zip(*columns, strict=True):
139
+ out = []
140
+ for v in row:
141
+ if v is None or (isinstance(v, float) and not np.isfinite(v)):
142
+ out.append("")
143
+ elif isinstance(v, (float, np.floating)):
144
+ out.append(f"{float(v):.8g}")
145
+ else:
146
+ out.append(str(v))
147
+ writer.writerow(out)
148
+ return str(path)