nhanes-mcp
Summary: nhanes-mcp is an MCP server for design-correct, conversational analysis of NHANES public-use data — it locates files, merges them on SEQN, selects and rescales the correct survey weight, and returns design-based estimates with NCHS reliability flags.
Orient —
list_cycles(supported cycles, file-name conventions, weight rules) andanalysis_guidance(the validity rules the server enforces; read before analyzing).Find data —
list_files(files by cycle and component: Demographics, Dietary, Examination, Laboratory, Questionnaire),search_variables(regex search across cycles/components, defaults to 2017–2018),describe_variable(codebook label, question text, target population, value codes, observed distribution, and flags for refused/don't-know codes).Build a dataset —
build_datasetjoins a DEMO universe to requested tables onSEQNacross one or more cycles, auto-picks and rescales the most restrictive analysis weight intoWT_ANALYSIS, and can optionally join the Linked Mortality File;describe_datasetreports columns, non-missing counts, weight choice, derived definitions and warnings.Clean and derive —
set_missing(recode sentinel refused/don't-know values),derive_variable(expression-based new variables withany/all/nonemissingness propagation),flag_from_long_table(collapse multi-row-per-person files like prescriptions or dietary recalls into one 0/1 flag, avoiding weight duplication).Analyze —
survey_estimate(design-based mean, proportion or total with domains, grouping, NCHS age adjustment, Korn–Graubard CIs and reliability flags),survey_frequency(weighted Table-1 style distributions with optional labels),survey_regression(survey-weighted linear or logistic),survey_cox(survey-weighted Cox PH with Binder variance, for use with mortality data).Export —
export_datasetwrites the analytic dataset with design variables to CSV plus a provenance sidecar.Data handling — downloads from cdc.gov on first use with caching in
~/.cache/nhanes-mcp(overridable), or works offline from a local.xptfolder; covers 1999–2000 through 2017–2018, 2017–March 2020 pre-pandemic, and August 2021–August 2023, with public-use data only.Optional add-on — the separately licensed (PolyForm Noncommercial) NHANES Results Explorer renders interactive views (headline estimate with CI and reliability badge, crude/age-adjusted toggle, subgroup panels, warnings, benchmarks) in MCP Apps hosts.
Schema gap — the README advertises 17 tools including
show_resultsandset_weight, but neither appears in this schema (15 tools present).
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@nhanes-mcp What is the prevalence of obesity among US adults in 2017–March 2020?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
nhanes-mcp
An MCP server for design-correct, conversational access to NHANES public-use data. Black Swan Causal Labs · MIT license · v0.5 · PyPI · MCP Registry
Most "chat with a dataset" layers let an agent compute an unweighted mean. With NHANES that
answer is wrong. This server makes the defensible analysis the default: the agent asks a question
in plain language, and the server finds the files, merges them on SEQN, picks the right weight,
keeps the full survey design, and reports design-based estimates with NCHS reliability flags.
Not affiliated with, or endorsed by, NCHS or CDC. Data are the public-use NHANES files published by the National Center for Health Statistics and downloaded directly from cdc.gov. Users are responsible for following the NCHS data use agreement.
What it handles for you
Pitfall | What the server does |
Wrong / no weight |
|
Subsetting before estimation |
|
Pooling cycles | Weights rescaled by cycle years / total years (2017–March 2020 counts as 3.2 years); 1999–2002 uses 4-year weights; strata made cycle-unique; refuses 2017–2018 + 2017–2020 overlap |
Long-format tables (e.g. prescriptions) | Refuses to join tables with repeated |
Refused / don't-know codes |
|
Silent 0 for missing |
|
Irregular file names | Tries known variants (e.g. 1999–2000 surplus-serum files |
Variance | Taylor linearization, strata × PSU, design df; Korn–Graubard CIs and NCHS 2017 reliability flags for proportions |
Age adjustment | Direct adjustment to the 2000 US standard (20–39 / 40–59 / 60+) with linearized SE, or to any caller-supplied standard (age groups + population), with a warning for in-domain records outside the groups |
Mortality | Optional join of the public-use Linked Mortality File (follow-up through 2019) and a design-based Cox model |
Related MCP server: NIH Research MCP Demo
Tools (17)
Step | Tools |
Orient |
|
Find |
|
Build |
|
Clean / derive |
|
Analyze |
|
Present |
|
Export |
|
Cycles: 1999–2000 through 2017–2018, 2017–March 2020 (pre-pandemic, P_ files) and August 2021–August 2023.
Results Explorer (optional add-on)
show_results returns design-based results as text plus structured data in every client. With the
optional NHANES Results Explorer add-on installed, MCP Apps hosts (Claude Desktop/web, ChatGPT,
VS Code, Goose) also render an interactive view: headline estimate with CI and NCHS reliability badge,
a crude / age-adjusted toggle that re-runs the estimate on the server, the analysis plan, subgroup
panels, server warnings, benchmarks against published estimates, and design provenance.
The add-on is a separate package from Black Swan Causal Labs under the PolyForm Noncommercial
License 1.0.0 (free for academic, public-health and other noncommercial use; commercial use needs a
license — https://blackswancausallabs.com). It is not part of this MIT repository. nhanes-mcp finds it if
it is installed in the same Python environment, if NHANES_MCP_EXPLORER_PATH points to it, or if a
folder named nhanes-mcp-explorer sits next to the nhanes-mcp folder.
Validation
Estimates were checked against published NCHS results (validation/):
Prevalence: 57 of 57 published NCHS estimates reproduced (Data Briefs 360, 363, 508, 515; pooled 2015–2018; 2017–March 2020 pre-pandemic).
Standard errors: 20 of 20 match; 11 of 12 published 95% CI bounds identical (the 12th differs by 0.1 at a rounding edge).
Mortality: a design-based Cox model on NHANES 1999–2006 (adults 25+) reproduces 6 of 7 published hazard ratios within their CIs (NHSR 155). The Mexican American contrast does not reproduce (0.71 vs 1.12 published); this is under investigation and the linked file here has longer follow-up (2019 vs 2015).
Hypertension (NCHS Data Brief 511, 2021–2023, adults 18+): prevalence (crude and age-adjusted, by sex and age), awareness, treatment and control — 17 of 17 published estimates reproduced exactly.
CMV seroprevalence (Bate et al., Clin Infect Dis 2010; NHANES 1999–2004, ages 6–49, surplus-serum weights): see
tests/benchmark_nchs.py. Before v0.4 the server silently used MEC weights here and could not load the 1999–2000 file.Unit tests (
tests/): variance checked against an independent loop implementation and a delete-one-PSU jackknife; Cox model checked against statsmodels PHReg and a jackknife; weight selection, pooling, guards, expression semantics, long-table and dietary-weight handling.
Install
Easiest: let your AI assistant do it
Paste this into Claude (Cowork or Claude Code), or any agent that can run commands on your computer:
Install the nhanes-mcp MCP server (PyPI package
nhanes-mcp) for Claude Desktop. Installuvif it is missing, then add this entry to my Claude Desktop config (claude_desktop_config.json), using the full path touvx:"nhanes": {"command": "uvx", "args": ["nhanes-mcp"]}. Keep my existing servers. Then tell me to restart Claude Desktop.
One line in the config (uvx)
With uv installed, add to claude_desktop_config.json and restart Claude Desktop
(on macOS use the full path from which uvx, e.g. /Users/<you>/.local/bin/uvx):
"nhanes": {
"command": "uvx",
"args": ["nhanes-mcp"]
}uvx fetches the server from PyPI into an isolated environment on
first launch; no clone or virtual environment to manage. To run the latest code from GitHub instead, use
"args": ["--from", "git+https://github.com/Black-Swan-Causal-Labs/nhanes-mcp", "nhanes-mcp"].
From source (for development)
python3 -m venv ~/.nhanes-mcp-venv
~/.nhanes-mcp-venv/bin/pip install "mcp>=1.2,<2" pandas numpy scipy pyreadstat httpx beautifulsoup4 lxml
git clone https://github.com/Black-Swan-Causal-Labs/nhanes-mcp.git ~/nhanes-mcp"nhanes": {
"command": "/Users/<you>/.nhanes-mcp-venv/bin/python",
"args": ["-m", "nhanes_mcp"],
"env": {"PYTHONPATH": "/Users/<you>/nhanes-mcp"}
}Any MCP client that runs local stdio servers works the same way. Data are downloaded from
cdc.gov on first use and cached in ~/.cache/nhanes-mcp (override with NHANES_MCP_CACHE).
Set NHANES_MCP_DATA_DIR to a folder of manually downloaded .xpt files to work offline.
Need help setting it up for your team, or adapting it to another survey or dataset? Contact Black Swan Causal Labs.
Tests
python tests/test_offline.py # synthetic NHANES-shaped data, no network
python tests/test_cox.py
python tests/test_long_and_dietary.py
python tests/benchmark_nchs.py # reproduces published NCHS estimates (needs network)Known open issues
Age-adjusted adult obesity for 2009–2010 and earlier runs 0.1–0.7 points below NCHS Health E-Stat 111 (2011–2012 onward matches exactly). Pooling and pregnancy-code handling were ruled out; cause under investigation.
The CMV analysis finds 14,198 tested participants aged 6–49 in the public surplus-serum files versus 15,310 reported by Bate et al.; unexplained.
NHANES III (1988–1994) is not supported.
Changelog
0.5.1 — First release on PyPI (
uvx nhanes-mcp) and the official MCP Registry (com.blackswancausallabs/nhanes-mcp). Packaging metadata only; no analysis changes.0.5.0 —
show_resultstool (text + structured results; interactive view via the optional Results Explorer add-on); one-command install withuvx; analysis guidance rule 11.0.4.1 — Comparisons inside missing-aware functions now return missing when an operand is missing, so skip-pattern definitions such as
where(BPQ020 == 1, fillna(BPQ150, 2) == 1, 0)are missing (not 0) for people never asked the screener. Hypertension benchmark (NCHS Data Brief 511) added.0.4.0 — Surplus-serum and other file-specific subsample weights with
2Y/4Ysuffixes are detected and pooled; 1999–2000_Afile names resolved;build_dataset(weight=...)and newset_weighttool, both recorded in every result; design columns protected fromderive_variable; missing-aware expression functions; custom age standards; CMV benchmark added.0.3.0 — Initial public release.
Limitations
Public-use files only. Restricted-use data (including the NHANES–CMS Medicare/Medicaid linkage) require an NCHS Research Data Center.
Variance uses Taylor linearization with PSUs treated as sampled with replacement, as NCHS recommends; replicate weights are not used.
The server reports what the data support; it does not choose a study design for you.
Available Tools
15 toolsanalysis_guidanceA
Rules for valid NHANES estimation that this server enforces. Read before analyzing.
Inputs: no named parameters. Returns: result
build_datasetA
Build an analysis-ready dataset: DEMO universe (all participants, needed for valid domain estimation) left-joined to the requested tables on SEQN, for one or more cycles.
tables: base names without cycle suffix, e.g. ["BMX", "TCHOL", "BPQ"] (DEMO is always included). variables: columns to keep from those tables (default: all). Weight/design variables are always kept. The analysis weight is chosen and rescaled automatically -> column WT_ANALYSIS.
Inputs: cycles (required), tables (required), variables, include_mortality.
derive_variableA
Create a variable from an expression over existing columns, e.g. name='OBESE', expression='BMXBMI >= 30' (booleans become 0/1). missing: 'any' -> result missing if ANY referenced column is missing (default, conservative); 'all' -> missing only if ALL referenced columns are missing (for OR-type definitions); 'none' -> no propagation.
Inputs: name (required), dataset_id (required), expression (required), missing.
describe_datasetC
Columns, non-missing counts, weight choice, derived-variable definitions and warnings.
Inputs: dataset_id (required).
describe_variableB
Codebook entry (label, question text, target population, value codes) plus observed distribution. Flags codes that look like refused/don't-know so they can be set to missing.
Inputs: cycle (required), table (required), variable (required).
export_datasetA
Write the analytic dataset (with WT_ANALYSIS, SDMVSTRA_U, SDMVPSU) to CSV plus a provenance sidecar.
Inputs: dataset_id (required), filename.
flag_from_long_tableA
Add a per-person 0/1 indicator from a file with several rows per participant (e.g. RXQ_RX
prescriptions, DR1IFF foods). Flag = 1 if ANY row's value in ANY of columns matches the regex
pattern (case-insensitive), e.g. table='RXQ_RX', columns=['RXDRSC1','RXDRSC2','RXDRSC3'],
pattern='^G40' for ICD-10 epilepsy as the reason for use. People absent from the file are missing.
Inputs: name (required), table (required), columns (required), pattern (required), +1 more.
list_cyclesA
List NHANES cycles this server supports, their file-name conventions and weight rules.
Inputs: no named parameters.
list_filesC
List data files for a cycle and component (Demographics, Dietary, Examination, Laboratory, Questionnaire).
Inputs: cycle (required), component (required).
search_variablesA
Search NHANES variable names/descriptions (regex, case-insensitive) across cycles/components. Defaults to the 2017-2018 cycle and all components.
Inputs: query (required), limit, cycles, components.
set_missingC
Recode sentinel values (e.g. 7, 9, 77, 99 for refused/don't know) to missing.
Inputs: codes (required), variable (required), dataset_id (required).
survey_coxA
Survey-weighted Cox proportional hazards model (Breslow ties, Binder linearized variance; same estimator as SUDAAN SURVIVAL / R svycoxph). Typical use with include_mortality=True: time='PERMTH_INT' (or PERMTH_EXM), event='MORTSTAT', domain including 'ELIGSTAT == 1'. Categorical predictors must be dummy-coded first with derive_variable.
Inputs: time (required), event (required), dataset_id (required), predictors (required), +1 more.
survey_estimateA
Design-based estimate (Taylor linearization) of a mean, proportion (0/1 variable) or total. domain: expression defining the subpopulation, e.g. 'RIDAGEYR >= 20 & RIDEXPRG != 1' (the design is NOT subset; out-of-domain records get zero weight). by: grouping variables, e.g. ['RIAGENDR']. age_adjust: 'nchs_adults_20plus' for NCHS direct age standardization (2000 census; 20-39/40-59/60+). Proportions come with Korn-Graubard CIs and NCHS reliability flags.
Inputs: variable (required), dataset_id (required), by, domain, +2 more.
survey_frequencyA
Weighted distribution of a categorical variable (Table 1 style): for each level, unweighted n, weighted percent, SE and Korn-Graubard CI, within the domain and optionally by group. labels: optional {code: label} map, e.g. {"1": "Male", "2": "Female"}.
Inputs: variable (required), dataset_id (required), by, domain, +1 more.
survey_regressionA
Survey-weighted linear ('gaussian') or logistic ('binomial') regression with design-based SEs. Categorical predictors must be dummy-coded first with derive_variable.
Inputs: outcome (required), dataset_id (required), predictors (required), domain, +1 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 15 tools
Each tool maps to a distinct NHANES workflow step: discovery, variable lookup, dataset construction, cleaning, derivation, and a specific survey estimator. Even similar pairs like describe_variable/describe_dataset and survey_estimate/survey_frequency are separated by clear resource and statistical-output differences.
The tools overwhelmingly follow a lowercase snake_case verb_noun pattern such as list_files, build_dataset, and export_dataset. Minor deviations like analysis_guidance and the survey_* family break the strict verb-first style, but the naming remains predictable and readable.
Fifteen tools is at the upper edge of the ideal range, but every tool earns its place by covering a necessary stage in the NHANES analysis pipeline. There is no redundancy or filler.
The toolkit covers the full analytic lifecycle: data discovery, codebook inspection, dataset assembly, missing-value handling, variable derivation, survey-weighted descriptive statistics, regression, survival analysis, and export. The analysis_guidance tool also addresses domain-specific estimation rules that would otherwise be a critical gap.
Maintenance
Related MCP Connectors
Search and query CDC public health data — mortality, vaccinations, surveillance, behavioral risk.
Unofficial CDC MCP — wraps CDC open data via Socrata API (data.cdc.gov)
Provide structured access to ClinicalTrials.gov data for searching, retrieving, and analyzing clin…
Query and summarize research data across tests and surveys
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables natural language exploration of OMOP CDM databases for concept discovery, patient count queries, and cohort SQL generation with support for multiple database backends.1MIT
- FlicenseAqualityDmaintenanceEnables interaction with synthetic NIH-style clinical research data through tools for searching publications, querying patient metadata, analyzing AAA measurements, and retrieving protocol guidance.5-
- AlicenseNot gradedqualityCmaintenanceEnables natural-language access to R maftools cancer genomics analyses, including mutation summaries, oncoplots, cohort comparisons, mutation signatures, clinical enrichment, survival analyses, and copy-number visualization.1MIT
- AlicenseAqualityBmaintenanceEnables querying the openFDA drug adverse event database for pharmacovigilance work-ups: case searches, counts and demographic/outcome breakdowns, disproportionality measures (ROR/PRR with Mantel-Haenszel adjustment), and empirical Bayes (MGPS/EBGM) signal scores, including bulk screening and stratification by sex, age, or year alongside confounder-adjusted analyses.151MIT