Skip to main content
Glama

English version: README.en.md

Mi Bridge (Mi Fitness Data Bridge)

Glama score

Локально-ориентированный мост данных, который экспортирует ваши собственные данные из приложения Xiaomi Mi Fitness в SQLite, JSON, CSV, Python и инструменты, совместимые с MCP.

Приложение Xiaomi Mi Fitness с радостью покажет вам ваши шаги, сон и пульс — но никогда не позволит забрать эти данные с собой. Этот мост помещает ваши собственные данные в файл SQLite на вашем собственном диске.

Товарный знак: Xiaomi, Mi Home, Mi Fitness являются товарными знаками Xiaomi Corporation. Этот проект является неофициальным сообществом и не имеет никакого отношения к Xiaomi Corporation и не одобрен ею.

Экспериментальный облачный адаптер может перестать работать в любой момент из-за изменений Xiaomi в частных интерфейсах. Используйте только с учётными записями и данными, к которым у вас есть право доступа.

Проверено на практике

Записано 2026-07-20 на Windows (Python 3.14) на основе коммита ветки main. Все данные синтетические, без каких-либо учётных данных или сетевого доступа. (Количество тестов повторно проверено и обновлено 2026-08-17.)

Тестовый набор:

$ python -m pytest -q -p no:cacheprovider
........................................................................ [ 96%]
...                                                                      [100%]
75 passed in 10.27s

Сквозная синтетическая демонстрация (examples/synthetic_demo.py сначала заполняет локальный кэш SQLite синтетическими записями, а затем запускает реальный конвейер экспорта JSON/CSV):

$ python examples/synthetic_demo.py
Seeded synthetic database: C:\Users\<you>\AppData\Local\Temp\mi-fitness-demo-53el7cfh\mi_fitness.db
  daily_activity: 2026-07-15 .. 2026-07-15 (1 day(s))
  sleep: 2026-07-14 .. 2026-07-14 (1 day(s))
  workouts: 2026-07-15 .. 2026-07-15 (1 day(s))
  body_measurements: 2026-07-15 .. 2026-07-15 (1 day(s))

Export completed
  mi_fitness.json
  daily_activity.csv
  sleep.csv
  workouts.csv
  body_measurements.csv
  heart_rate.csv
  spo2.csv
  stress.csv
  abnormal_heart_beat.csv

JSON envelope:
  schema_version: 1.0
  source: mi_fitness_data_bridge
  records.daily_activity: 1 row(s)
  records.sleep: 1 row(s)
  records.workouts: 1 row(s)
  records.body_measurements: 1 row(s)

Sample sleep row (synthetic):
  start_at=2026-07-14T23:20:00 end_at=2026-07-15T07:05:00
  duration_minutes=465 score=86
  stages=[{"stage": "deep", "minutes": 82}, {"stage": "light", "minutes": 271}, {"stage": "rem", "minutes": 88}, {"stage": "awake", "minutes": 24}]

Related MCP server: miband-mcp

Проект health-assistant объединён

Проект health-assistant (локально-ориентированная персональная панель здоровья: Strava, сон, состав тела, анализ питания) объединён в этот репозиторий, его исходный репозиторий архивирован. Перенесённые ресурсы находятся в каталоге docs/health-assistant/:

  • analytics.py — эталонная реализация движка рекомендаций по тренировкам/восстановлению без зависимостей (7-дневная статистика тренировок, соотношение острой/хронической нагрузки, проверка готовности, ежедневные рекомендации по тренировкам).

  • coaching_methodology.md — объяснимая методология велосипедного коучинга, состава тела и спортивного питания, лежащая в его основе.

  • README.md — полные инструкции по миграции, включая намеренно не перенесённые части (панель FastAPI, конвейер Strava OAuth/Webhook, анализ фотографий приёмов пищи) и причины.

Что делает этот проект

  • Читает данные Xiaomi Mi Fitness через экспериментальный облачный адаптер для китайского региона.

  • Сохраняет нормализованные записи в локальную базу данных SQLite.

  • Экспортирует переносимые JSON или CSV без учётных данных.

  • Предоставляет локальные инструменты запросов MCP для личной автоматизации.

  • Предоставляет переиспользуемую реализацию коннектора для нижестоящих проектов (например, персонального консультанта по снижению веса).

Он намеренно не предоставляет медицинские консультации, рекомендации по снижению веса, управляемый доступ к учётным записям или многопользовательские облачные сервисы.

Зачем нужен этот мост?

Раньше

Теперь

Ваша история здоровья существует только в приложении Xiaomi Mi Fitness, и единственный способ «экспорта» — скриншоты.

mi-fitness-bridge sync загружает ежедневную активность, сон, тренировки, измерения тела, пульс, SpO2 и стресс в нормализованную локальную базу данных SQLite.

Чтобы ответить на вопрос «как я спал в прошлом месяце», приходится листать приложение день за днём.

mi-fitness-bridge export --format csv --type sleep --start-date ... --end-date ... выводит CSV-файл, точно отфильтрованный по этому диапазону и готовый к открытию в табличном редакторе.

Чтобы дать AI-ассистенту доступ к вашим данным о здоровье, приходится передавать учётные данные какому-то хостинг-сервису.

mi-fitness-bridge serve предоставляет локальные инструменты запросов MCP на основе вашей собственной базы данных; passToken остаётся в связке ключей операционной системы и никогда не попадает в экспортируемые файлы.

Поддерживаемые наборы данных

  • Ежедневная активность: шаги, дистанция, активные калории и минуты активности.

  • Записи сна и фазы сна.

  • Записи тренировок.

  • Измерения тела: вес и доступные поля состава тела.

  • Сэмплы пульса, включая пульс в покое, когда доступен.

  • SpO2, стресс и события аномального сердцебиения (зависит от наличия в учётной записи/устройстве).

Фактическая доступность зависит от устройства, региона учётной записи, прошивки и вышестоящих сервисов Xiaomi.

Установка

git clone https://github.com/shkyyy18/mi-bridge.git mi_fitness_data_bridge
cd mi_fitness_data_bridge
python -m venv .venv

Windows PowerShell:

.\.venv\Scripts\Activate.ps1
pip install -e ".[dev]"

Windows Git Bash:

source .venv/Scripts/activate
pip install -e ".[dev]"

macOS/Linux:

source .venv/bin/activate
pip install -e '.[dev]'

Конфигурация

Более безопасный интерактивный путь настройки позволяет избежать записи passToken в историю shell:

mi-fitness-bridge setup
mi-fitness-bridge doctor

Когда доступно, учётные данные хранятся в локальной связке ключей (keyring). Некоторые запасные реализации keyring могут хранить ключи недостаточно безопасно; перед использованием ознакомьтесь с поведением keyring вашей операционной системы.

Как получить user_id и passToken

Этот мост использует учётные данные уровня учётной записи Xiaomi (та же сессия входа, что и в приложении Mi Home), выберите один из двух способов:

Способ 1: Ручное копирование в браузере

  1. Откройте account.xiaomi.com в браузере и войдите в свою учётную запись Xiaomi (та же учётная запись, что и в приложении Xiaomi Mi Fitness).

  2. Откройте инструменты разработчика (F12) → «Приложение / Application» → Cookies → https://account.xiaomi.com.

  3. Скопируйте значения cookie userId и passToken и вставьте их при запросе mi-fitness-bridge setup.

Способ 2: Инструмент входа по QR-коду

Войдите один раз по QR-коду с помощью open-source mijia-api:

pip install mijiaAPI
python -c "from mijiaAPI import mijiaAPI; mijiaAPI().login()"   # 终端出二维码,用米家 App 扫码

Состояние входа по умолчанию сохраняется в ~/.config/mijia-api/auth.json (на Windows — %USERPROFILE%\.config\mijia-api\auth.json); значения userId и passToken из него можно напрямую использовать в этом мосте — учётные данные уровня учётной записи Xiaomi универсальны для сервисов, и мост использует их для получения сессии Xiaomi Mi Fitness (sid=miothealth). Обратите внимание, что auth.json хранит учётные данные в открытом виде: после ввода userId и passToken в этот мост (системная связка ключей) рекомендуется удалить этот файл.

Примечания:

  • passToken истекает; при сообщении doctor об ошибке аутентификации просто получите его заново по шагам выше.

  • При использовании браузерного способа входите в систему в вашей обычной сетевой среде; частая или необычная активность может вызвать защиту учётной записи Xiaomi (слайдер/ SMS-верификация); при срабатывании защиты можно использовать способ с QR-кодом.

  • Имена cookie и процесс входа основаны на проверке от 2026-08 и могут отличаться в зависимости от региона учётной записи, устройства или политики защиты; Xiaomi также может в любой момент изменить частные интерфейсы (см. экспериментальное заявление вверху).

  • Эти два значения эквивалентны состоянию входа в вашу учётную запись; не разглашайте их и не коммитьте в Git.

Синхронизация

mi-fitness-bridge sync --start-date 2026-07-01 --end-date 2026-07-15

Или синхронизируйте только один набор данных:

mi-fitness-bridge sync --type sleep --start-date 2026-07-01 --end-date 2026-07-15
mi-fitness-bridge sync --type body_measurements --start-date 2026-07-01 --end-date 2026-07-15

База данных по умолчанию находится в каталоге данных пользователя платформы (определяется platformdirs). sync, export, serve, doctor поддерживают смену расположения через параметр --db или переменную окружения MI_FITNESS_DB_PATH, приоритет: командная строка > переменная окружения > расположение по умолчанию. Обратите внимание, что platformdirs на Windows не реагирует на переменную окружения LOCALAPPDATA; для настройки пути используйте два указанных выше способа:

mi-fitness-bridge sync --db ./data/mi_fitness.db --start-date 2026-07-01 --end-date 2026-07-15
export MI_FITNESS_DB_PATH=./data/mi_fitness.db

Известные ограничения: инкрементальная синхронизация без параметра даты начинается со времени последней локальной записи; исправления или дополнения более ранней истории на вышестоящем сервере не подтягиваются автоматически; при необходимости явно перезапустите этот диапазон с более ранним --start-date (будет идемпотентно перезаписано, без дублирующих записей).

Экспорт

Создание переносимого JSON-файла:

mi-fitness-bridge export --format json --output exports/mi_fitness.json

Отдельный CSV-файл для каждого набора данных:

mi-fitness-bridge export --format csv --output exports/csv

Фильтрация по набору данных и дате:

mi-fitness-bridge export --format json --type sleep \
  --start-date 2026-07-01 --end-date 2026-07-15 \
  --output exports/sleep.json

Экспортируемые файлы никогда не содержат сохранённый passToken Xiaomi, но содержат идентифицирующие столбцы, такие как user_id, в открытом виде — экспортируемые файлы являются чувствительными персональными данными, храните их надлежащим образом. Экспортированные записи о здоровье по умолчанию игнорируются Git.

Описание формата экспорта (структура JSON-конверта, структура CSV, правила фильтрации дат с закрытыми интервалами) см. в Export format.

MCP-сервис

Совместимая команда по-прежнему доступна:

mi-fitness-bridge serve
# legacy alias
mi-fitness-mcp serve

Доступные инструменты включают запросы статуса подключения, синхронизации, покрытия, ежедневных сводок, измерений тела, сна, тренировок, пульса, SpO2 и стресса, а также ориентированный на агентов инструмент временных рядов тренировок workout_series — автоматическое понижение частоты дискретизации с жёстким верхним пределом max_points (усреднение по фиксированным временным интервалам, агрегация внутри SQLite), с честным указанием downsampled, source_points, returned_points, method в ответе, а также полной статистикой полной точности (avg/min/max/квантили) и временем в пульсовых зонах. Инструменты списков/сводок, такие как query_workouts, get_daily_summary, сопровождаются data_quality (количество покрытых дней, отсутствующие метрики, время последней синхронизации).

Пример подключения клиента (конфигурационный JSON для MCP-клиентов, таких как Claude Code / Codex):

{
  "mcpServers": {
    "mi-bridge": {
      "command": "mi-fitness-bridge",
      "args": ["serve"]
    }
  }
}

Примечание: serve — это stdio-сервис, общающийся с клиентом через стандартный ввод-вывод, а не HTTP-сервис. Запуск его напрямую в терминале может выглядеть как «зависание» — это ожидание MCP-сообщений от клиента, что нормально; в повседневной работе запускайте его через MCP-клиент согласно конфигурации выше.

Использование в качестве Python-зависимости

Нормализованный адаптер по-прежнему доступен под совместимым именем модуля:

from mi_fitness_mcp.adapters.mi_fitness_cloud import MiFitnessCloudAdapter

Нижестоящие проекты должны устанавливать этот пакет, а не вендорить или копировать исходный код коннектора.

Лицензия

История лицензии: версии, выпущенные до 2026-08-03, лицензированы под MIT (атрибуция MIT вышестоящих kubulashvili/mi-fitness-mcp и binglua/mi-fitness-mcp-cn сохранена в блоке NOTICE вверху LICENSE); новый код текущей версии лицензирован под AGPL-3.0-only. Подробности см. в LICENSE и THIRD_PARTY_NOTICES.md.

Конфиденциальность и безопасность

  • Надлежащим образом храните passToken, локальную базу данных, экспортируемые файлы и журналы, не разглашайте их.

  • Экспортируемые файлы не содержат passToken, но содержат идентифицирующие столбцы, такие как user_id, в открытом виде — это также чувствительные персональные данные.

  • Не запускайте этот мост как публичный прокси учётных данных.

  • Не коммитьте реальные данные о здоровье или скриншоты с личными показателями.

  • В отчётах об ошибках и документации всегда используйте синтетические данные.

  • Это программное обеспечение предназначено только для доступа к личным данным и инженерных исследований, не для диагностики или лечения.

Ответственное раскрытие уязвимостей — см. SECURITY.md, происхождение — см. THIRD_PARTY_NOTICES.md.

Разработка

pip install -e '.[dev]'
python -m pytest -q -p no:cacheprovider
python -m ruff check src tests

Релизы

История версий — в CHANGELOG.md, чек-лист релиза и пост-релизных проверок — в docs/release-checklist.md.

Связанные проекты

  • garmin-mcp — локально-ориентированный MCP-сервис для данных Garmin. Разделяет с этим проектом контракт данных agent-safe-series/v1 (семантика полей понижения частоты дискретизации временных рядов побайтово совпадает), один и тот же AI-агент может без проблем потреблять данные обоих сервисов.

Поддержка проекта

Если этот инструмент вам помог, поставьте звезду на GitHub.

Available Tools

17 tools
cancel_syncA
Idempotent

Cancel a queued/running background MCP sync by its exact sync_id. Returns the terminal job status after cancellation completes; already-finished jobs are returned unchanged. Stops future requests without deleting or rolling back records already committed to SQLite; counts may be incomplete. Unknown IDs or foreground jobs return status=error. No new cloud request. Use get_sync_status to inspect progress and sync_data with user consent to resume via a new job.

Inputs: sync_id (required).

get_connection_statusA

Check whether the configured Mi Fitness account can connect before requesting a sync. May contact Xiaomi, authenticate and rotate credentials in the local keyring; does not sync health records. Requires local interactive CLI setup, never credentials in tool arguments. Returns connected, mode, last_sync_at and available_data_types; configured responses also include connection_state, region, last_connection_error and sync_in_progress. While syncing, reports existing connection state instead of probing. For cached date coverage use get_data_coverage.

Inputs: no named parameters.

get_data_coverageA
Read-onlyIdempotent

Inspect which date ranges already exist in the local cache before choosing query dates or requesting sync_data. Returns data.coverage [{data_type, first_date, last_date, days_with_data}] for nonempty datasets; omitted/empty data_types means all datasets. Empty datasets are omitted, and first/last dates do not guarantee uninterrupted coverage between them. This does not test cloud connectivity or report a background job; use get_connection_status or get_sync_status respectively. Read-only local SQLite query; no cloud request or automatic sync. Requires a configured local account/cache. Returns JSON text with status, source=cache, generated_at and data; empty lists mean no cached matches, not zero measurements. Use sync_data to refresh with user consent.

Inputs: data_types.

get_profileA
Read-onlyIdempotent

Read minimal metadata for the already-connected local account, not a medical or demographic profile. No cloud request or cache write; returns JSON text with status, source and data.profile containing account_id_masked, configured timezone and devices (currently an empty placeholder). Never returns credentials or plaintext account IDs. Returns status=error if disconnected; get_connection_status can establish/check the connection first. Use query_daily_activity for activity totals.

Inputs: no named parameters.

get_sync_statusA
Read-onlyIdempotent

Read one MCP sync job by sync_id, including after a server restart. Returns sync_id, status, timestamps and available result counts. States are queued, running, ok, partial, error, cancelled or interrupted (previous process stopped). Read-only local lookup; no cloud request. History retains the latest 500 completed jobs per account; unknown/expired IDs return status=error. Use query_sync_history to discover IDs, cancel_sync to stop a live background job, or get_connection_status for cloud connectivity. Restarted lookups omit raw error text for privacy.

Inputs: sync_id (required).

query_abnormal_heart_beatA
Read-onlyIdempotent

Read device-reported abnormal-heartbeat events starting within an inclusive YYYY-MM-DD range. Returns data.events [{event_id, start_at, end_at, duration_seconds}] and data.count, earliest first. limit defaults to 5000; use offset for subsequent pages. Events are upstream flags, not a diagnosis; an empty list is not evidence of a healthy heart. Use query_heart_rate for ordinary bpm samples, not this event list. Read-only local SQLite query; no cloud request or automatic sync. Requires a configured local account/cache. Returns JSON text with status, source=cache, generated_at and data; empty lists mean no cached matches, not zero measurements. Use get_data_coverage to inspect availability or sync_data to refresh with user consent. Returns data.pagination {limit, offset, has_more, next_offset}; next_offset is null at the end. Keep filters unchanged and avoid syncing between pages.

Inputs: end_date (required), start_date (required), limit, offset.

query_body_measurementsA
Read-onlyIdempotent

Read timestamped body measurements over an inclusive YYYY-MM-DD range. Returns data.measurements and data.count in timestamp order; latest_only=true returns only the last matching record, not the latest value of each field. Omitted/empty metrics returns all available fields; otherwise timestamp plus selected fields, with absent optional measurements omitted. Units are kg for mass, percent for body fat/water, dimensionless for BMI. Use query_metric_series(metric=weight_kg) for a daily or aggregated weight trend. latest_only selects before pagination. Read-only local SQLite query; no cloud request or automatic sync. Requires a configured local account/cache. Returns JSON text with status, source=cache, generated_at and data; empty lists mean no cached matches, not zero measurements. Use get_data_coverage to inspect availability or sync_data to refresh with user consent. Returns data.pagination {limit, offset, has_more, next_offset}; next_offset is null at the end. Keep filters unchanged and avoid syncing between pages.

Inputs: end_date (required), start_date (required), limit, offset, +2 more.

query_daily_activityA
Read-onlyIdempotent

Choose this for a multi-column daily activity table, not a single-metric trend. Read daily activity totals: steps, distance_m, active_kcal, total_kcal, floors and active_minutes, plus data_quality. Supply date for one day or both start_date/end_date for an inclusive YYYY-MM-DD range; date takes precedence if both forms are given. Returns data.summaries and data.data_quality. Missing optional upstream metrics may appear as zero with quality warnings; do not treat them as confirmed measurements. For one metric across days/weeks/months use query_metric_series; sleep and workouts have separate tools. Read-only local SQLite query; no cloud request or automatic sync. Requires a configured local account/cache. Returns JSON text with status, source=cache, generated_at and data; empty lists mean no cached matches, not zero measurements. Use get_data_coverage to inspect availability or sync_data to refresh with user consent. Returns data.pagination {limit, offset, has_more, next_offset}; next_offset is null at the end. Keep filters unchanged and avoid syncing between pages.

Inputs: date, limit, offset, end_date, +1 more.

query_heart_rateA
Read-onlyIdempotent

Read timestamped heart-rate samples in bpm over an inclusive YYYY-MM-DD range, optionally filtering sample_type. Returns data.samples [{timestamp, bpm, sample_type}] and data.count, earliest first. limit defaults to 5000; use a smaller page/date window for large datasets. The cloud adapter normally stores resting/active/passive, so sample_type=workout may be empty; use query_workout_series with a workout_id to analyze all samples in that activity window. Not a diagnosis. Read-only local SQLite query; no cloud request or automatic sync. Requires a configured local account/cache. Returns JSON text with status, source=cache, generated_at and data; empty lists mean no cached matches, not zero measurements. Use get_data_coverage to inspect availability or sync_data to refresh with user consent. Returns data.pagination {limit, offset, has_more, next_offset}; next_offset is null at the end. Keep filters unchanged and avoid syncing between pages.

Inputs: end_date (required), start_date (required), limit, offset, +1 more.

query_metric_seriesA
Read-onlyIdempotent

Build a dated trend for steps (count), distance_m (meters), active_kcal (kcal), or weight_kg (kg) over an inclusive YYYY-MM-DD range. Returns data.metric and data.series [{date, value}], sorted ascending, without filling missing dates. Activity uses daily totals; weight uses the latest stored measurement per day. granularity=day returns these daily values; week groups from Monday, month from the first day. aggregation (default sum) applies only to week/month daily values; latest selects the last available day. Prefer avg or latest for weight. For raw body readings use query_body_measurements; heart-rate samples use query_heart_rate; one workout uses query_workout_series. Read-only local SQLite query; no cloud request or automatic sync. Requires a configured local account/cache. Returns JSON text with status, source=cache, generated_at and data; empty lists mean no cached matches, not zero measurements. Use get_data_coverage to inspect availability or sync_data to refresh with user consent. Returns data.pagination {limit, offset, has_more, next_offset}; next_offset is null at the end. Keep filters unchanged and avoid syncing between pages.

Inputs: metric (required), end_date (required), start_date (required), limit, +3 more.

query_sleepA
Read-onlyIdempotent

Read sleep sessions (start-date filtered) and a main-sleep summary (local wake-date filtered) over an inclusive YYYY-MM-DD range. Returns data.sessions, count, main_sessions, metrics and data_quality; main sleep is the longest valid non-nap per wake date. include_naps defaults true and affects the raw list only, not main-sleep selection. Times include start_at/end_at; durations are minutes; sleep_score/source can be null and missing scores are not zero. Expand dates around midnight if needed; raw counts can differ from wake-date summary counts. Use this instead of query_daily_activity for sleep. Pagination affects sessions/count only; main_sessions, metrics and quality still describe the full date range, so keep ranges narrow. Read-only local SQLite query; no cloud request or automatic sync. Requires a configured local account/cache. Returns JSON text with status, source=cache, generated_at and data; empty lists mean no cached matches, not zero measurements. Use get_data_coverage to inspect availability or sync_data to refresh with user consent. Returns data.pagination {limit, offset, has_more, next_offset}; next_offset is null at the end. Keep filters unchanged and avoid syncing between pages.

Inputs: end_date (required), start_date (required), limit, offset, +1 more.

query_spo2A
Read-onlyIdempotent

Read stored blood oxygen saturation samples (spo2_pct, percent) over an inclusive YYYY-MM-DD range. Returns data.samples [{timestamp, spo2_pct}] and data.count, earliest first. limit defaults to 5000; use offset for subsequent pages. These are device measurements, not a diagnosis; missing records do not indicate normal oxygen levels. Use query_heart_rate for bpm rather than oxygen saturation. Read-only local SQLite query; no cloud request or automatic sync. Requires a configured local account/cache. Returns JSON text with status, source=cache, generated_at and data; empty lists mean no cached matches, not zero measurements. Use get_data_coverage to inspect availability or sync_data to refresh with user consent. Returns data.pagination {limit, offset, has_more, next_offset}; next_offset is null at the end. Keep filters unchanged and avoid syncing between pages.

Inputs: end_date (required), start_date (required), limit, offset.

query_stressA
Read-onlyIdempotent

Read device stress samples over an inclusive YYYY-MM-DD range, optionally filtered by level (low/medium/high). Returns data.samples [{timestamp, stress_score, level}] and data.count, earliest first. stress_score is the upstream device score, not a clinical assessment. limit defaults to 5000; use offset for subsequent pages. Use query_sleep for sleep quality rather than inferring it from stress. Read-only local SQLite query; no cloud request or automatic sync. Requires a configured local account/cache. Returns JSON text with status, source=cache, generated_at and data; empty lists mean no cached matches, not zero measurements. Use get_data_coverage to inspect availability or sync_data to refresh with user consent. Returns data.pagination {limit, offset, has_more, next_offset}; next_offset is null at the end. Keep filters unchanged and avoid syncing between pages.

Inputs: end_date (required), start_date (required), level, limit, +1 more.

query_sync_historyA
Read-onlyIdempotent

List this account's MCP sync jobs, newest first, from persistent local SQLite. Returns data.jobs and data.pagination with timestamps, statuses, available counts and safe error codes, never credentials, raw errors or health records. Includes foreground/background jobs started since this feature was installed, not CLI syncs; retains the latest 500 completed jobs plus active jobs. Read-only, no cloud calls. Use get_sync_status for one ID and cancel_sync for a live background job. Empty jobs means no retained history. Returns data.pagination {limit, offset, has_more, next_offset}; next_offset is null at the end. Keep filters unchanged and avoid syncing between pages.

Inputs: limit, offset.

query_workoutsA
Read-onlyIdempotent

List recorded workouts starting within an inclusive YYYY-MM-DD range. Returns data.workouts, count and data_quality; rows include workout_id, activity_type, start_at/end_at, duration_minutes, distance_m, calories_kcal and available heart-rate/pace fields (missing fields may be null). activity_types matches case-insensitively; min_duration is minutes and min_distance_km is kilometers (unlike output distance_m). Filters combine with AND before pagination. Use a returned workout_id with query_workout_series for a heart-rate curve; this tool returns session summaries, not samples. Read-only local SQLite query; no cloud request or automatic sync. Requires a configured local account/cache. Returns JSON text with status, source=cache, generated_at and data; empty lists mean no cached matches, not zero measurements. Use get_data_coverage to inspect availability or sync_data to refresh with user consent. Returns data.pagination {limit, offset, has_more, next_offset}; next_offset is null at the end. Keep filters unchanged and avoid syncing between pages.

Inputs: end_date (required), start_date (required), limit, offset, +3 more.

query_workout_seriesA
Read-onlyIdempotent

Read an auto-downsampled heart-rate curve for one workout_id obtained from query_workouts (contract agent-safe-series/v1). Uses all cached heart-rate sample types inside the workout window. Returns data with numeric t offsets in seconds from start_time, bpm values, downsampled/source_points/returned_points/method and full-resolution summary statistics. resolution defaults to 60 seconds and increases to respect max_points (default 400, hard cap 500). Pass the same reference_max_hr in bpm for comparable time_in_zone across activities; otherwise each workout uses its own maximum, so zones are not comparable. Unknown workout IDs or unsupported metrics return status=error. For raw date-range samples use query_heart_rate. Read-only local SQLite query; no cloud request or automatic sync. Requires a configured local account/cache. Returns JSON text with status, source=cache, generated_at and data; empty lists mean no cached matches, not zero measurements. Use get_data_coverage to inspect availability or sync_data to refresh with user consent.

Inputs: workout_id (required), metric, max_points, resolution, +1 more.

sync_dataA

Download selected Mi Fitness datasets from Xiaomi into local SQLite; writes records and sync watermarks, may authenticate/rotate local credentials, and does not modify cloud health records. Requires local CLI setup and user authorization to access the account. Omitted data_types selects all adapter-supported types; an empty list is invalid. Dates are inclusive YYYY-MM-DD; start_date must not exceed end_date. Omitted end_date uses today; omitted start_date resumes the watermark or uses configured lookback (default 30 days). force_full_sync ignores the watermark, not the requested date range, and does not erase the database. Only one sync runs at a time. background=false waits for status ok/partial/error, sync_id, record counts and per-type results; background=true returns accepted plus sync_id to poll with get_sync_status. Partial results may already be stored; inspect results before retrying. Use cached query tools instead when no refresh is needed.

Inputs: end_date, background, data_types, start_date, +1 more.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A4.6/5.0

    Scored across 17 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose: query_* tools target specific health data types or aggregation levels, while sync lifecycle tools (connection, sync, status, cancel, history, coverage) are well separated. Descriptions explicitly cross-reference related tools to resolve potential overlaps (e.g., metric series vs daily activity vs raw body measurements).

    Naming Consistency5/5

    All names use consistent snake_case with predictable verb prefixes: get_ for system/status reads, query_ for cached data reads, and sync/cancel for actions. Minor singular/plural variation (query_workouts vs query_workout_series) is semantically meaningful and not confusing.

    Tool Count4/5

    17 tools is slightly above the typical 3–15 range but justified by the breadth of distinct health metrics and sync management operations. No tool appears redundant; each query tool maps to a unique data type or purpose.

    Completeness4/5

    The surface covers connection, sync lifecycle, cache coverage, profile, and queries for all major Mi Fitness data types (activity, body, heart rate, sleep, workouts, SpO2, stress, abnormal beats). Minor gaps like sleep stages or workout GPS details may exist, but agents can work around them.

    Maintenance

    ActivityActive
    ResponsivenessUsually handled

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      C
      quality
      C
      maintenance
      Enables reading and syncing Xiaomi Mi Fitness health data (steps, heart rate, sleep, workouts) from the Chinese cloud region to a local SQLite database via MCP tools.
      10
      21
      MIT
    • F
      license
      Not graded
      quality
      C
      maintenance
      Enables AI to query Xiaomi Mi Band health data (steps, sleep, heart rate) from Gadgetbridge SQLite exports via the MCP protocol, allowing natural language questions about daily activity.
      1
      -
    • A
      license
      Not graded
      quality
      B
      maintenance
      Lets AI assistants read your own Mi Fitness (Xiaomi cloud) health data — steps, heart rate, sleep, SpO2, stress, weight and workouts — through local MCP tools with QR-code login. Runs locally over stdio, returns results as JSON, and withholds GPS tracks unless explicitly allowed.
      629 PyPI
      9
      MIT
    • A
      license
      C
      quality
      B
      maintenance
      Enables AI clients to query and analyze your own Xiaomi/Mi Fitness health data — daily activity, minute-level heart rate, sleep stages, workouts, body composition, SpO₂, stress, and abnormal heart beat events — after syncing it from the Xiaomi cloud into a local SQLite database. Exposes 14 tools covering connection status, incremental sync control, and metric/date-range queries, with everything stored and served locally.
      14
      MIT