Skip to main content
Glama

M4: Infrastructure for AI-Assisted Clinical Research

M4 is infrastructure for AI-assisted clinical research. Initialize MIMIC-IV, eICU, or custom datasets as fast local databases (with optional BigQuery for cloud access). Your AI agents get specialized tools (MCP, Python API) and clinical knowledge (agent skills) to query and analyze them.

Usage example – M4 MCP | Usage example – Code Execution

M4 builds on the M3 project. Please cite their work as well when using M4!

Why M4?

Clinical research shouldn't require mastering database schemas. Whether you're screening a hypothesis, characterizing a cohort, or running a multi-step survival analysis—you should be able to describe what you want and get clinically meaningful results.

M4 makes this possible by giving AI agents deep clinical knowledge:

Understand clinical semantics. LLMs can write SQL, but have a harder time with (dataset-specific) clinical semantics. M4's comprehensive agent skills encode validated clinical concepts—so "find sepsis patients" produces clinically correct queries on any supported dataset.

Work across modalities. Clinical research with M4 spans structured data, clinical notes, and (soon) waveforms and imaging. M4 dynamically selects tools based on what each dataset contains—query labs in MIMIC-IV, search discharge summaries in MIMIC-IV-Note, all through the same interface.

Go beyond chat. Data exploration and simple research questions work great via MCP. But real research requires iteration: explore a cohort, compute statistics, visualize distributions, refine criteria. M4's Python API returns DataFrames that integrate with pandas, scipy, and matplotlib—turning your AI assistant into a research partner that can execute complete analysis workflows.

Cross-dataset research. You should be able to ask for multi-dataset queries or cross-dataset comparisons. M4 makes this easier than ever as the AI can switch between your initialized datasets on its own, allowing it to do cross-dataset tasks for you.

Interactive exploration. Some research tasks—like cohort definition—benefit from real-time visual feedback rather than iterative text queries. M4 Apps embed purpose-built UIs directly in your AI client, letting you drag sliders, toggle filters, and see instant results without leaving your workflow.

Related MCP server: OMOP MCP Server

Quickstart (3 steps)

1. Install uv

macOS/Linux:

curl -LsSf https://astral.sh/uv/install.sh | sh

Windows (PowerShell):

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

2. Initialize M4

mkdir my-research && cd my-research
uv init && uv add m4-infra
source .venv/bin/activate  # Windows: .venv\Scripts\activate
m4 init mimic-iv-demo

This downloads the free MIMIC-IV demo dataset (~16MB) and sets up a local DuckDB database.

3. Connect your AI client

Claude Desktop:

m4 config claude --quick

Other clients (Cursor, LibreChat, etc.):

m4 config --quick

Copy the generated JSON into your client's MCP settings, restart, and start asking questions!

  • If you don't want to use uv, you can just run pip install m4-infra

  • If you want to use Docker, look at docs/DEVELOPMENT.md

Code Execution

For complex analysis that goes beyond simple queries, M4 provides a Python API that returns Python data types instead of formatted strings (e.g. pd.DataFrame for SQL queries). This transforms M4 from a query tool into a complete clinical data analysis environment.

from m4 import execute_query, get_schema

dataset = "mimic-iv"

# Get schema as a dict
schema = get_schema(dataset=dataset)
print(schema['tables'])  # ['mimiciv_hosp.admissions', 'mimiciv_hosp.diagnoses_icd', ...]

# Query returns a pandas DataFrame
df = execute_query("""
    SELECT icd_code, COUNT(*) as n
    FROM mimiciv_hosp.diagnoses_icd
    GROUP BY icd_code
    ORDER BY n DESC
    LIMIT 10
""", dataset=dataset)

# Use full pandas power: filter, join, compute statistics
df[df['n'] > 100].plot(kind='bar')

The API uses the same tools as the MCP server, so behavior is consistent. But instead of parsing text, you get DataFrames you can immediately analyze, visualize, or feed into downstream pipelines.

When to use code execution:

  • Multi-step analyses where each query informs the next

  • Large result sets (thousands of rows) that shouldn't flood your context

  • Statistical computations, survival analysis, cohort characterization

  • Building reproducible analysis notebooks

See Code Execution Guide for the full API reference and this example session for a walkthrough.

Agent Skills

M4 ships with a set of skills that teach AI coding assistants clinical research patterns. Skills activate automatically when relevant—ask about "SOFA scores" or "sepsis cohorts" and Claude uses validated SQL from MIT-LCP repositories.

For the canonical list of bundled skills, see src/m4/skills/SKILLS_INDEX.md.

Clinical skills:

  • Severity Scores: SOFA, APACHE III, SAPS-II, OASIS, LODS, SIRS

  • Sepsis: Sepsis-3 cohort identification, suspected infection

  • Organ Failure: KDIGO AKI staging

  • Measurements: GCS calculation, baseline creatinine, vasopressor equivalents

  • Cohort Selection: First ICU stay identification

  • Research Methodology: Common research pitfalls and how to avoid them

System skills:

  • M4 Framework: Python API usage, research workflow, setup repair, vitrine display, skill creation guide

  • Data Structure: MIMIC-IV table relationships, MIMIC-eICU mapping

Supported tools: Claude Code, Cursor, Cline, Codex CLI, Gemini CLI, GitHub Copilot

m4 skills                                    # Interactive tool and skill selection
m4 skills --tools claude,cursor              # Install all skills for specific tools
m4 skills --tools claude --tier validated     # Only validated skills
m4 skills --tools claude --category clinical  # Only clinical skills
m4 skills --tools claude --skills sofa-score,m4-api  # Specific skills by name
m4 skills --list                             # Show installed skills with metadata

See Skills Guide for the full list and how to create custom skills.

M4 Apps

M4 Apps bring interactivity to clinical research. Instead of text-only responses, apps render interactive UIs directly in your AI client—ideal for tasks that benefit from real-time visual feedback.

Cohort Builder: Define patient cohorts with live filtering. Adjust age ranges, add diagnosis codes, and toggle clinical criteria while watching counts update instantly.

User: Help me build a cohort of elderly diabetic patients
Claude: [Launches Cohort Builder UI with interactive filters]

M4 Apps require a host that supports the MCP Apps protocol (like Claude Desktop). In other clients, you'll get text-based results instead.

See M4 Apps Guide for details on available apps and how they work.

Example Questions

Once connected, try asking:

Tabular data (mimic-iv, eicu):

  • "What tables are available in the database?"

  • "Show me the race distribution in hospital admissions"

  • "Find all ICU stays longer than 7 days"

  • "What are the most common lab tests?"

Derived concept tables (mimic-iv, after m4 init-derived):

  • "What are the average SOFA scores for patients with sepsis?"

  • "Show KDIGO AKI staging distribution across ICU stays"

  • "Find patients on norepinephrine with SOFA > 10"

  • "What is the 30-day mortality for patients with Charlson index > 5?"

Clinical notes (mimic-iv-note):

  • "Search for notes mentioning diabetes"

  • "List all notes for patient 10000032"

  • "Get the full discharge summary for this patient"

Supported Datasets

Dataset

Modality

Size

Access

Local

BigQuery

Derived Tables

mimic-iv-demo

Tabular

100 patients

Free

Yes

No

No

mimic-iv

Tabular

365k patients

PhysioNet credentialed

Yes

Yes

Yes

mimic-iv-note

Notes

331k notes

PhysioNet credentialed

Yes

Yes

No

mimic-iv-ed-demo

Tabular

100 patients

Free

Yes

Yes

No

mimic-iv-ed

Tabular

425k ED stays

PhysioNet credentialed

Yes

Yes

No

eicu-demo

Tabular

2.5k ICU stays

Free

Yes

Yes

No

eicu

Tabular

200k+ ICU stays

PhysioNet credentialed

Yes

Yes

No

mimic-iii

Tabular

40k+ patients

PhysioNet credentialed

Yes

Yes

No

mimic-cxr-jpg

Tabular, Imaging

377k chest X-rays

PhysioNet credentialed

Yes

No

No

MIMIC-CXR-JPG's images are half a terabyte: M4 downloads its tables, and m4 fetch-images mimic-cxr-jpg --from-csv cohort.csv fetches the images of a cohort (paths from mimic_cxr.images.image_path).

These datasets are supported out of the box. A folder of your own CSV files becomes a dataset with m4 define-dataset NAME --src DIR and m4 init NAME --src DIR; other datasets can be added by following these instructions.

Choose datasets explicitly at each call site and switch the saved backend anytime:

m4 backend bigquery # Switch to BigQuery (or duckdb)
m4 capabilities     # Show available interfaces, datasets, tools, and policies
m4 doctor           # Diagnose local, BigQuery, and MCP setup
m4 status --dataset mimic-iv # Show dataset and backend status
m4 status --all     # List all available datasets
m4 status --dataset mimic-iv --derived # Show per-table derived materialization status

For automation and external agents, M4 also provides non-interactive JSON commands that use request-scoped dataset and backend options:

m4 agent-env --dataset mimic-iv --backend duckdb --json
m4 capabilities --json
m4 doctor --json
m4 download mimic-iv --json
m4 list-datasets --json --no-interactive
m4 schema --dataset mimic-iv --backend duckdb --json --no-interactive
m4 describe-table mimiciv_hosp.patients --dataset mimic-iv --json --no-interactive
m4 query --dataset mimic-iv --sql "SELECT COUNT(*) AS n FROM mimiciv_hosp.patients" --json --no-interactive
m4 provenance export --json

Machine-facing status and backend metadata hide local filesystem paths by default. Use --paths or M4_PATH_DISCLOSURE=1 only when the caller is allowed to see raw local paths.

Long-running dataset setup can emit newline-delimited JSON progress events:

m4 init mimic-iv --json --events ndjson --no-interactive --download \
  --physionet-credentials-file /path/to/physionet-credentials.json
m4 init-derived mimic-iv --json --events ndjson

When --events ndjson is used, stdout is an NDJSON stream instead of a single JSON object. The final result is emitted as operation_completed.result; setup failures are emitted as operation_failed.error.

Derived concept tables (MIMIC-IV only):

m4 init-derived mimic-iv         # Materialize derived tables (SOFA, sepsis3, KDIGO, etc.)
m4 init-derived mimic-iv --list  # List available derived tables without materializing

After running m4 init mimic-iv, you are prompted whether to materialize derived tables. You can also run m4 init-derived separately at any time. Derived tables are created in the mimiciv_derived schema (e.g., mimiciv_derived.sofa) and are immediately queryable. The SQL is vendored from the mimic-code repository -- production-tested and DuckDB-compatible. BigQuery users already have these tables available via physionet-data.mimiciv_derived and do not need to run init-derived.

  1. Get PhysioNet credentials: Complete the credentialing process and sign the data use agreement for the dataset.

  2. Download the data with M4:

    cat > physionet-credentials.json <<'JSON'
    {
      "username": "YOUR_USERNAME",
      "password": "YOUR_PASSWORD"
    }
    JSON
    
    m4 init mimic-iv --download --physionet-credentials-file physionet-credentials.json

    Do not pass PhysioNet passwords as command-line flags. Use a scoped credentials file with restrictive permissions and delete it after setup.

    M4 implements the same recursive, resumable pattern PhysioNet documents for wget -r -N -c -np against /files/... dataset URLs, while preserving the expected raw layout under m4_data/raw_files/<dataset>/.

    You can still download manually if needed:

    m4 download mimic-iv

    For credentialed datasets, m4 download validates the expected local layout and prints a dataset-specific resumable wget command.

    # For MIMIC-IV
    wget -r -N -c -np --cut-dirs=3 -nH --user YOUR_USERNAME --ask-password \
      https://physionet.org/files/mimiciv/3.1/ \
      -P m4_data/raw_files/mimic-iv
    
    # For eICU
    wget -r -N -c -np --cut-dirs=3 -nH --user YOUR_USERNAME --ask-password \
      https://physionet.org/files/eicu-crd/2.0/ \
      -P m4_data/raw_files/eicu

    The --cut-dirs=3 -nH flags remove the PhysioNet files/<dataset>/<version>/ prefix so CSV files land under m4_data/raw_files/<dataset>/ with only dataset-internal folders preserved.

  3. Initialize after a manual download:

    m4 init mimic-iv   # or: m4 init eicu

This converts the CSV files to Parquet format and creates a local DuckDB database.

Available Tools

M4 exposes these tools to your AI client. Data tools are checked against the explicit dataset selected for that call.

Dataset Management:

Tool

Description

list_datasets

List available datasets and their status

set_dataset

Removed migration aid; pass dataset to data tools

Tabular Data Tools (every dataset except mimic-iv-note):

Tool

Description

get_database_schema

List all available tables

get_table_info

Get column details and sample data

execute_query

Run SQL SELECT queries

Clinical Notes Tools (mimic-iv-note):

Tool

Description

search_notes

Full-text search with snippets

get_note

Retrieve a single note by ID

list_patient_notes

List notes for a patient (metadata only)

M4Bench

M4Bench is the benchmark built on M4: 28 clinical EHR derivation tasks on MIMIC-IV and eICU that measure how well coding agents reproduce reference clinical concepts, with and without skills.

More Documentation

Guide

Description

Architecture

Design philosophy, system overview, clinical semantics

Code Execution

Python API for programmatic access

M4 Apps

Interactive UIs for clinical research tasks

Skills

Clinical and system skills for AI-assisted research

Tools Reference

MCP tool documentation

BigQuery Setup

Google Cloud for full datasets

Custom Datasets

Add your own data or other PhysioNet datasets

M4Bench Reproducibility

MIMIC-IV/eICU initialization and benchmark reruns

Development

Contributing, testing, code style

OAuth2 Authentication

Enterprise security setup

Roadmap

M4 is infrastructure for AI-assisted clinical research. Current priorities:

  • Clinical Semantics

    • More concept mappings (comorbidity indices, medication classes)

    • Semantic search over clinical notes (beyond keyword matching)

    • More agent skills that provide meaningful clinical knowledge

  • New Modalities

    • Waveforms (ECG, arterial blood pressure)

    • Imaging (chest X-rays)

  • Clinical Research Agents

    • Skills and guardrails that enforce scientific integrity and best practices (documentation, etc.)

    • Query logging and session export

    • Result fingerprints for audit trails

Troubleshooting

"Parquet not found" error:

m4 init mimic-iv-demo --force

m4 status shows a dataset as incomplete: An initialization was interrupted, a raw file came into M4's raw folder after it finished, or the dataset was initialized by M4 0.5.5 or earlier, which did not record that it finished. Run m4 init <dataset> again: with the same --src to go on with a run that read from another folder, without it to convert what is in M4's own raw folder. Only what is missing is redone, and a download that did not finish is completed first.

MCP client won't connect: Check client logs (Claude Desktop: Help → View Logs) and ensure the config JSON is valid.

m4 command opens GNU M4 instead of the CLI: On macOS/Linux, m4 is a built-in system utility. Make sure your virtual environment is activated (source .venv/bin/activate) so that the correct m4 binary is found first. Alternatively, use uv run m4 [command] to run within the project environment without activating it.

Need to reconfigure:

m4 config claude --quick   # Regenerate Claude Desktop config
m4 config --quick          # Regenerate generic config

Citation

If you use M4 or M4Bench, please cite the M4Bench paper:

@inproceedings{ill2026m4bench,
  title={M4Bench: Evaluating Procedural Specification for Clinical EHR Derivation Agents},
  author={Ill, Hannes and Al Attrach, Rafi and Fani, Rajna and Han, Ahram and Yamamoto, Ryohei and Moerig, Marlene Louisa and Yoon, Dukyong and Celi, Leo Anthony},
  booktitle={Advances in Neural Information Processing Systems (NeurIPS), Evaluations and Datasets Track},
  year={2026}
}

M4 builds on the M3 project. Please also cite M3 when using this repository:

@article{attrach2025conversational,
  title={Conversational LLMs Simplify Secure Clinical Data Access, Understanding, and Analysis},
  author={Attrach, Rafi Al and Moreira, Pedro and Fani, Rajna and Umeton, Renato and Celi, Leo Anthony},
  journal={arXiv preprint arXiv:2507.01053},
  year={2025}
}

Available Tools

11 tools
capabilitiesA

Return the M4 capability manifest as JSON.

Inputs: no named parameters. Returns: result

cohort_builderA

Launch the interactive cohort builder.

Opens a visual interface for filtering patients by demographics and clinical criteria. See live patient counts as you adjust filters.

Requires: A host that supports MCP Apps (like Claude Desktop). For non-UI hosts, returns dataset information as text.

Returns: Dataset info and welcome message. UI hosts will render the interactive cohort builder interface.

Inputs: dataset. Returns: result

execute_queryA

🚀 Execute SQL queries to analyze data.

Recommended workflow:

  1. Use get_database_schema() to list tables

  2. Use get_table_info() to examine structure

  3. Write your SQL query with exact names

Args: dataset: Dataset name, e.g. 'mimic-iv'. sql_query: Your SQL SELECT query (SELECT only).

Returns: Query results or helpful error messages.

Inputs: sql_query (required), dataset. Returns: result

get_database_schemaA

📚 Discover what data is available in the database.

When to use: Start here to understand what tables exist.

Args: dataset: Dataset name, e.g. 'mimic-iv'.

Returns: List of all available tables in the database with current backend info.

Inputs: dataset. Returns: result

get_noteA

📄 Retrieve full text of a specific clinical note.

Warning: Clinical notes can be very long. Consider using search_notes() first to find relevant notes, or use max_length to truncate output.

Args: dataset: Dataset name, e.g. 'mimic-iv-note'. note_id: The note ID (e.g., from search_notes or list_patient_notes). max_length: Optional maximum characters to return (truncates if exceeded).

Returns: Full note text, or truncated version if max_length specified.

Inputs: note_id (required), dataset, max_length. Returns: result

get_table_infoA

🔍 Explore a specific table's structure and see sample data.

When to use: After identifying relevant tables from get_database_schema().

Args: dataset: Dataset name, e.g. 'mimic-iv'. table_name: Exact table name (case-sensitive). show_sample: Whether to include sample rows (default: True).

Returns: Table structure with column names, types, and sample data.

Inputs: table_name (required), dataset, show_sample. Returns: result

list_datasetsA

📋 List all available datasets and their status.

Returns: A formatted string listing available datasets, indicating selected status, and showing availability of local database and BigQuery support.

Inputs: no named parameters. Returns: result

list_patient_notesA

📋 List available clinical notes for a patient.

Returns note metadata (IDs, types, lengths) without full text. Use get_note(note_id) to retrieve specific notes.

Cross-dataset tip: Get subject_id from MIMIC-IV queries, then use it here to find related clinical notes.

Args: dataset: Dataset name, e.g. 'mimic-iv-note'. subject_id: Patient identifier (same as in MIMIC-IV). note_type: Type of notes to list ('discharge', 'radiology', or 'all'). limit: Maximum notes to return (default: 20).

Returns: List of available notes with metadata for the patient.

Inputs: subject_id (required), limit, dataset, note_type. Returns: result

query_cohortA

Query cohort counts based on filtering criteria.

Used by the cohort builder UI for live updates as users adjust filters. Can also be called directly to get cohort statistics.

Args: dataset: Dataset name, e.g. 'mimic-iv'. age_min: Minimum patient age (0-130, inclusive). age_max: Maximum patient age (0-130, inclusive). gender: Patient gender ('M' or 'F'). icd_codes: List of ICD diagnosis code prefixes to filter by. icd_match_all: If True, patient must have ALL ICD codes (AND); default is ANY (OR). has_icu_stay: If True, require ICU stay; if False, exclude ICU patients. in_hospital_mortality: If True, require in-hospital death; if False, exclude deaths.

Returns: JSON with patient_count, admission_count, demographics, and SQL.

Inputs: gender, age_max, age_min, dataset, +4 more. Returns: result

search_notesA

🔍 Search clinical notes by keyword.

Returns snippets around matches to prevent context overflow. Use get_note() to retrieve full text of specific notes.

Note types: 'discharge' (summaries), 'radiology' (reports), or 'all'

Args: dataset: Dataset name, e.g. 'mimic-iv-note'. query: Search term to find in notes. note_type: Type of notes to search ('discharge', 'radiology', or 'all'). limit: Maximum number of results per note type (default: 5). snippet_length: Characters of context around matches (default: 300).

Returns: Matching snippets with note IDs for follow-up retrieval.

Inputs: query (required), limit, dataset, note_type, +1 more. Returns: result

set_datasetD

Deprecated: M4 no longer keeps a global active dataset.

Inputs: dataset_name (required). Returns: result

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    B3.4/5.0

    Scored across 11 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose: database exploration (get_database_schema, get_table_info, execute_query), note handling (search_notes, list_patient_notes, get_note), cohort building (cohort_builder, query_cohort), and meta tasks (capabilities, list_datasets). The deprecated set_dataset is clearly marked, avoiding confusion.

    Naming Consistency4/5

    Most tools follow a consistent verb_noun snake_case pattern (e.g., execute_query, get_note, list_datasets). However, 'capabilities' is a plain noun and 'cohort_builder' is noun_noun, breaking the pattern slightly.

    Tool Count5/5

    11 tools is well-scoped for a medical data analysis server. Each tool covers a necessary operation without overlap or redundancy, and the count feels balanced for the domain.

    Completeness4/5

    The tool surface covers core workflows: database discovery, SQL querying, note retrieval and search, and cohort filtering. A minor gap is the lack of a direct patient demographics tool, but SQL queries can retrieve that information.

    Maintenance

    ActivityMaintained
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables querying MIMIC-IV medical data using natural language through MCP clients, with support for local DuckDB and cloud BigQuery backends.
      80
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables natural language exploration of OMOP CDM databases for concept discovery, patient count queries, and cohort SQL generation with support for multiple database backends.
      1
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables exploring a synthetic electronic health record via natural language, including patient demographics, encounters, notes, and medications, with optional write support for adding synthetic progress notes.
      -
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables natural-language cohort discovery and querying of human-subject research data, building cohorts and retrieving results while respecting Chiron's access controls.
      MIT