Skip to main content
Glama
PAP Analytics MCP

PAP Analytics MCP

by drew2323

pap-analytics-mcp

Ask your AI agent how you slept on CPAP – and get answers grounded in your own device data.

CI Release Python 3.12+ MCP License: MIT

An MCP server that turns PAP therapy data (CPAP / APAP / BiPAP / ASV) into small, aggregate tools an AI agent can call. The agent gets usage, AHI, events, leak, pressure and SpO2 – not megabytes of raw waveforms – so you can simply ask:

  • "How was last night?"

  • "Which parts of the night had the most events, and what kind?"

  • "Analyse the hypopnea at 3:12 – what happened right before it?"

  • "Did my SpO2 drop after the events?"

  • "Compare this week with last week."

πŸŽ™οΈ Talk it through by voice

Add the server as an MCP connector to a voice assistant (ChatGPT Voice, or other voice apps with MCP support such as Dots, Muse or Grok) and ask the same questions out loud instead of reading charts. The assistant answers from your own device data. Setup: run the HTTP server and make it reachable for the app (e.g. via a tunnel); see client integration.

Features

  • πŸŒ™ Night summaries, time windows and period comparisons: from a whole night down to single breaths, or one week against another.

  • πŸ”Ž Anomaly finder that points at event clusters, large leak, desaturations and pressure at maximum.

  • 🫁 Oximetry (SpO2, pulse, T90, ODI) when an oximeter is connected.

  • 🏷️ Clear provenance: every number says whether it came from the device or was computed here.

  • πŸ”’ Local and read-only: source data is never modified, and everything is stored on your machine (DuckDB + Parquet).

  • 🧩 Device-agnostic core: vendors plug in as adapters. ResMed is available today.

Related MCP server: sleepon-mcp

Supported devices

Vendor

Devices

Source

ResMed

AirSense 11 (tested, also with airbreak-plus); other AirSense/AirCurve 10/11 with the same SD-card layout should work

SD card or a copy of it, e.g. the AirCANnect share

LΓΆwenstein

planned

–

The source directory is the SD-card root, which contains Identification.*, STR.edf and DATALOG/.

Quick start

1. Install (needs uv):

uv tool install "git+https://github.com/drew2323/pap-analytics-mcp@v0.1.4"

Add --with matplotlib if you also want PNG plots (plot_segment).

2. Configure: create ~/.config/pap-analytics/config.toml:

[[sources]]
name = "my-airsense"
path = "/media/SDCARD"          # SD-card root or a copy of it
timezone = "Europe/Prague"      # the device's clock timezone

3. Import and check:

pap doctor /media/SDCARD        # optional: what was found on the card
pap ingest                      # import (incremental; re-run any time)
pap nights --days 7             # one row per night

No data at hand? In a checkout, uv run pap ingest --source tests/data/resmed-air11-autoset imports the bundled sample nights.

Connect your agent

Claude Desktop / Claude Code / any stdio MCP client:

{
  "mcpServers": {
    "pap": { "command": "pap", "args": ["serve", "--stdio", "--read-only"] }
  }
}

Use the full path (e.g. ~/.local/bin/pap) if the client does not see your PATH.

Over HTTP (another machine, e.g. over a VPN). This always requires a bearer token:

PAP_HTTP_TOKEN=$(openssl rand -hex 32) pap serve --http --read-only    # 127.0.0.1:8765/mcp
claude mcp add --transport http pap http://127.0.0.1:8765/mcp --header "Authorization: Bearer $PAP_HTTP_TOKEN"

--read-only hides the admin ingest tool. Without it, the agent can trigger an import itself.

MCP tools

Every tool returns compact JSON with units and provenance (device or derived). Dates are YYYY-MM-DD, last or yesterday; times are local HH:MM within the night (a night runs from noon to noon).

Tool

What it does

list_devices

Known devices, their data range and when data was last imported

list_nights

One row per night: usage, AHI (device and derived), events, leak and pressure p95, oximetry flag

night_summary

Full picture of one night: sessions, mask-off gaps, events per hour, metrics, settings in effect, SpO2

find_anomalies

Ranked parts of a night worth a look (event clusters, large leak, desaturations, pressure at max, outliers vs. the last 14 nights), each with a reason and a suggested next call

get_events

Events in a time window, optionally filtered by type (obstructive, central, hypopnea, RERA, …)

segment_stats

Min/median/mean/p95/max of every channel plus the events inside a window, e.g. 02:00–02:30

get_signal

One channel (flow, pressure, leak, resp. rate, tidal volume, SpO2, …) downsampled to ≀ 2000 points

get_signals

Several channels on one time grid at full resolution, for a close look at a short window (breath by breath)

oximetry_summary

SpO2 and pulse: mean, minimum, T90, ODI 3 %/4 %, hypoxic burden, list of desaturations, artefacts filtered out

disturbance_summary

Disturbances beyond AHI in a night or window: pulse response to events, rapid pulse rises and their breathing response, hypoxic burden, flow limitation, calm vs. restless breathing, inspiratory flow shape (NED, Glasgow Index; split by pressure support) (measured) and possible arousals / RERA candidates (inferred, kept separate), with timestamps

disturbance_trend

The same disturbance metrics as one comparable row per night, with means over the range

compare_periods

Average nightly metrics of two periods with the absolute and relative change; optionally the nightly disturbance and flow-shape metrics too (e.g. before/after a pressure change)

get_settings

Device settings in effect on a date, or the full history of changes

plot_segment

PNG chart of a window with events shaded (needs matplotlib)

ingest

Admin: import new data now (hidden with --read-only)

Also available: the resources pap://glossary (channels, units, event types) and pap://devices, and the prompt nightly_review (a guided review of one night). The same queries work on the command line: pap nights, pap night last, pap segment last 02:10 02:40.

Configuration

Everything lives in one TOML file: ~/.config/pap-analytics/config.toml, $PAP_CONFIG or --config FILE. The full annotated example is config.example.toml.

Key

Default

Meaning

[[sources]] path

– (required)

Directory to read; repeat [[sources]] for more devices

[[sources]] name

–

Short label (required when using sync)

[[sources]] timezone

Europe/Prague

Timezone of the device clock

[[sources]] adapter

auto

Force a vendor adapter, e.g. resmed

store_dir

~/.local/share/pap-analytics

Where imported data lives (disposable, rebuildable)

day_boundary_hour

12

A "night" runs from noon to noon, like in ResMed/OSCAR

[http] host / port / token_file

127.0.0.1 / 8765 / –

HTTP transport

[thresholds] <key>

built-in defaults

Optional analytics overrides (leak, clusters, pressure, oximetry, outliers); every supported key, default, unit and range is listed in config.example.toml

[sources.sync]

–

Optional rsync pull of the data from another host

Environment overrides: PAP_CONFIG, PAP_STORE_DIR, PAP_DAY_BOUNDARY_HOUR, PAP_HTTP_HOST, PAP_HTTP_PORT, PAP_HTTP_TOKEN, PAP_HTTP_TOKEN_FILE. Run pap config show to print the effective configuration (secrets redacted).

Fresh data automatically: run pap ingest --watch or use the systemd timer in deploy/systemd/. To pull the data from another machine, see [sources.sync] in OPERATIONS.

Docker

cp compose.example.yaml compose.yaml   # + config.toml with Docker paths, token in ./secrets/
docker compose up -d                   # ingest (watch) + MCP over HTTP on 127.0.0.1:8765

Details, secrets and the stdio fallback: docs/OPERATIONS.md.

Under the hood

Not just a thin wrapper around files – the server has its own analytics layer:

  • Ingest: own EDF/EDF+ reader and vendor adapters normalise the data into one vendor-neutral model; imports are incremental.

  • Store: DuckDB catalog plus per-channel Parquet signals, rebuildable from the source at any time.

  • Analytics: window statistics, event clustering, anomaly ranking, SpO2 (T90, ODI, desaturations, hypoxic burden), disturbances beyond AHI (pulse responses, flow limitation, breath-by-breath breathing stability and inspiratory flow shape, possible arousals), period comparison, settings history.

  • Interface: 15 MCP tools, resources and a prompt over stdio or HTTP (bearer token) – for desktop agents, coding agents and voice assistants.

Python 3.12, NumPy, PyArrow, the official MCP SDK; matplotlib optional. Details in ARCHITECTURE.

Development

uv sync
uv run pytest && uv run ruff check .

The tests run against real ResMed nights published as fixtures in tests/data/. Before contributing, read AGENTS.md (repository rules) and docs/ARCHITECTURE.md.

CLAUDE.md points Claude Code to AGENTS.md, which is the single source of repository rules. Work is tracked as GitHub issues: one issue = one PR (body contains Closes #<n>), developed in its own git worktree, merged after the local quality gate and CI are green. Details are in the Workflow and Delivery sections of AGENTS.md.

Doc

Content

ARCHITECTURE

Components, canonical data model, contracts

OPERATIONS

Runtimes, config reference, sync, deploy, troubleshooting

DECISIONS

Architecture decision log

plan/

Implementation work packages

License

MIT. Parts of the EDF handling are derived from airbreak-plus (MIT).

Available Tools

14 tools
compare_periodsA

Mean nightly metrics for period A and B with absolute and relative delta (B βˆ’ A). include_disturbances=true adds the nightly disturbance_trend metrics (pulse, flow limitation, breathing stability, flow shape NED/Glasgow, RERA candidates), e.g. to compare nights before and after a pressure change; slower (about 1-3 s per night).

Inputs: a_to (required), b_to (required), a_from (required), b_from (required), +2 more. Returns: object

disturbance_summaryC

Sleep disturbances beyond AHI for a night or a window: measured (pulse rate response to events, rapid pulse rises with their breathing response, hypoxic burden, flow limitation, calm vs restless breathing, inspiratory flow shape NED/Glasgow Index) and inferred (possible autonomic arousals, RERA candidates from device flow limitation and from NED) metrics, flow_shape_by_ps (flow shape split by pressure support 0 / > 0), plus timestamped findings (incl. restless breathing periods) and per-event pulse responses. Inferred items are not scored arousals/RERAs; calm/restless is not sleep staging.

Inputs: date (required), end, start, device_id. Returns: object

disturbance_trendB

Nightly disturbance metrics (PRR, pulse-rise index, hypoxic burden, flow limitation, calm-breathing share, flow shape: NED and Glasgow Index, inferred arousal, NED RERA and RERA-candidate indices) one row per night, with units/methods and the mean per metric. Default: the last 14 days of data. Null = signal missing that night.

Inputs: date_to, date_from, device_id. Returns: object

find_anomaliesB

Parts of a night worth a look (event clusters, large leak, desaturations, pressure at max, low ventilation, mask-off gaps, metric outliers vs the last 14 nights), most severe first, each with a plain-English reason and a suggested_call to inspect it.

Inputs: date (required), device_id. Returns: object

get_eventsC

Events in a window of the therapy day (default: whole night). start/end are HH:MM within the therapy day or ISO datetimes; types filters by canonical event type.

Inputs: date (required), end, limit, start, +2 more. Returns: object

get_settingsB

Device settings: those in effect on date, or the full history of change points.

Inputs: date, device_id. Returns: object

get_signalC

A channel downsampled to at most max_points (hard cap 2000) buckets of min/mean/max. flow and pressure_hr only for windows up to 30 min.

Inputs: end (required), date (required), start (required), channel (required), +2 more. Returns: object

get_signalsA

Raw samples of several channels (e.g. flow, pressure_hr, mask_pressure, pressure, spo2) on ONE time grid, no aggregation and no interpolation. The grid step is that of the finest channel (25 Hz -> 0.04 s); a slower channel has its real sample on matching rows and null elsewhere. Row i is at start + i * step_s (no time list). Limit: 2000 rows (80 s with a 25 Hz channel; slow channels alone can span much longer). For longer windows use get_signal (aggregated).

Inputs: end (required), date (required), start (required), channels (required), +1 more. Returns: object

list_devicesA

Known devices with their data range and the time of the last ingest.

Inputs: no named parameters. Returns: object

list_nightsB

One row per night (usage, AHI device+derived, events, leak/pressure p95, oximetry flag). Default: the last 14 days of data. Dates: YYYY-MM-DD, last, yesterday.

Inputs: date_to, date_from, device_id. Returns: object

night_summaryB

Detail of one night: sessions, mask-off gaps, events, device vs derived metrics, channel statistics, settings in effect and oximetry. date = YYYY-MM-DD or last.

Inputs: date (required), device_id. Returns: object

oximetry_summaryB

SpO2/pulse metrics (mean, min, T90, ODI3/4, pulse) with artefact filtering and the desaturation list for a night or a window. available=false when there is no valid SpO2.

Inputs: date (required), end, start, device_id. Returns: object

plot_segmentA

PNG plot of a night segment (pressure, leak, minute ventilation, SpO2 by default) with events as shaded bands. Use for a visual check of a window found by find_anomalies.

Inputs: end (required), date (required), start (required), channels, +1 more.

segment_statsA

Statistics (min/p5/p50/mean/p95/max, coverage) of channels and the events inside a time window, e.g. date=2026-11-08 start=02:00 end=02:30 (local time within the therapy day).

Inputs: end (required), date (required), start (required), channels, +1 more. Returns: object

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.5/5.0

    Scored across 14 tools

    Disambiguation4/5

    Most tools target clearly distinct resources: nights, devices, events, settings, oximetry, disturbances, anomalies, and plotting are each covered by one obvious tool. The riskiest pair is `get_signal` vs `get_signals` (downsampled single channel vs raw multi-channel on a shared grid), and the three '*_summary' tools (night, disturbance, oximetry) could be initially confused, though descriptions explicitly separate them and cross-reference the right alternative.

    Naming Consistency4/5

    Names follow two coherent families: verb_noun actions (get_signal, get_signals, get_events, get_settings, list_nights, list_devices, compare_periods, find_anomalies, plot_segment) and noun_qualified analytical views (night_summary, oximetry_summary, disturbance_summary, disturbance_trend, segment_stats). The get_/list_ prefixing is predictable, with the only real deviation being near-identical singular/plural names and mixed noun-only vs verb-prefixed retrieval tools.

    Tool Count5/5

    At 14 tools the set sits comfortably in the well-scoped range, and each tool covers a distinct layer of the analytics workflow: discovery (devices, nights), drill-down (night_summary, events, segment_stats), signal access (get_signal/get_signals), specialized domains (oximetry, settings, disturbances), and synthesis (compare_periods, find_anomalies, plot_segment). No tool appears redundant or token-padding.

    Completeness4/5

    The read-only analytics surface is broad: device/night discovery, per-night detail, event and window statistics, aggregated and raw signal access, oximetry, settings history, disturbance trends, period comparison, anomaly triage, and visual plotting. Minor gaps existβ€”no consolidated long-range adherence/compliance rollup or export of results, and anomaly findings can only be followed up through generic segment tools rather than a dedicated 'explain finding' callβ€”but agents can work around these via compare_periods, list_nights, and segment_stats.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      Not graded
      maintenance
      Enables AI assistants to access and analyze Oura Ring health data including sleep, readiness, activity, and stress metrics. Supports customizable queries, correlation analysis, and visualization capabilities for comprehensive health insights.
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to analyze sleep quality, compare nights, generate reports, and get personalized improvement tips using Sleepon sleep tracker data.
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Query Apple Health export data with an LLM via a semantic layer that avoids common data traps, enabling accurate natural-language queries about health metrics. Optionally imports CPAP therapy data for correlation.
      3
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to query health metrics such as activity, blood pressure, glucose, heart rate, sleep, and SpO2 from a PostgreSQL-backed wellness database, returning structured data and summaries through MCP tools.
      -