Skip to main content
Glama

미차오 (Mi Fitness Data Bridge)

영어 버전: README.en.md

미차오 (Mi Fitness Data Bridge)

Glama score

로컬 우선 데이터 브리지로, 여러분 소유의 미 피트니스(Mi Fitness) 데이터를 SQLite, JSON, CSV, Python 및 MCP 호환 도구로 내보냅니다.

미 피트니스(Mi Fitness) 앱은 걸음 수, 수면, 심박수를 보여주는 데는 인색하지 않지만, 데이터를 가져가는 것은 절대 허용하지 않습니다. 이 브리지는 여러분의 데이터를 여러분 하드 드라이브의 SQLite 파일에 담아드립니다.

상표 고지: 샤오미, 미가, Mi Fitness는 샤오미의 상표입니다. 이 프로젝트는 비공식 커뮤니티 프로젝트로, 샤오미와 아무런 관련이 없으며 보증되지 않습니다.

실험적인 클라우드 어댑터는 샤오미가 비공개 API를 변경하면 언제든지 중단될 수 있습니다. 액세스 권한이 있는 계정과 데이터에 대해서만 사용하세요.

테스트 검증

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/웹훅 파이프라인, 식사 사진 분석)과 그 이유를 포함한 전체 마이그레이션 지침.

이 프로젝트가 하는 일

  • 실험적인 중국 지역 클라우드 어댑터를 통해 미 피트니스(Mi Fitness) 데이터를 읽습니다.

  • 정규화된 레코드를 로컬 SQLite 데이터베이스에 저장합니다.

  • 자격 증명이 없는 휴대용 JSON 또는 CSV로 내보냅니다.

  • 개인 자동화를 위한 로컬 MCP 쿼리 도구를 노출합니다.

  • 다운스트림 프로젝트(예: 개인 체지방 감량 컨설턴트)를 위한 재사용 가능한 커넥터 구현을 제공합니다.

의도적으로 의학적 조언, 체중 감량 지침, 관리형 계정 액세스 또는 다중 사용자 클라우드 서비스를 제공하지 않습니다.

왜 이 브리지인가?

이전

이후

건강 기록은 미 피트니스(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은 OS 키체인에 유지되며 내보내기 파일에 절대 포함되지 않습니다.

지원되는 데이터 세트

  • 일일 활동: 걸음 수, 거리, 활동 칼로리 및 활동 시간.

  • 수면 기록 및 수면 단계.

  • 운동 기록.

  • 체중 및 사용 가능한 체성분 필드를 포함한 신체 측정.

  • 심박수 샘플(가능한 경우 안정 시 심박수 포함).

  • 혈중 산소 포화도(SpO2), 스트레스 및 비정상 심장 박동 이벤트(계정/기기에서 제공하는 경우).

실제 가용성은 기기, 계정 지역, 펌웨어 및 샤오미 업스트림 서비스에 따라 다릅니다.

설치

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을 셸 기록에 직접 입력하지 않아도 되는 더 안전한 대화형 구성 경로:

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

가능한 경우 자격 증명은 로컬 키링(keyring)에 저장됩니다. 일부 대체 keyring 구현은 키를 안전하지 않은 방식으로 저장할 수 있으므로 사용 전에 운영 체제의 keyring 동작을 숙지하세요.

user_id 및 passToken 얻는 방법

이 브리지는 샤오미 계정 수준 자격 증명(미홈 앱과 동일한 로그인 상태)을 사용합니다. 다음 두 가지 방법 중 하나를 선택하세요:

방법 1: 브라우저에서 수동으로 복사

  1. 브라우저에서 account.xiaomi.com을 열고 샤오미 계정(미 피트니스(Mi Fitness) 앱과 동일한 계정)으로 로그인합니다.

  2. 개발자 도구(F12) → '애플리케이션 / Application' → 쿠키 → https://account.xiaomi.com을 엽니다.

  3. userId 및 passToken 쿠키 값을 복사하고 mi-fitness-bridge setup에서 메시지가 표시되면 붙여넣습니다.

방법 2: QR 코드 로그인 도구

오픈 소스 mijia-api로 한 번 QR 코드 로그인:

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을 이 브리지에 직접 사용할 수 있습니다. 샤오미 계정 수준 자격 증명은 서비스 전반에 걸쳐 공통이며, 브리지는 이를 사용하여 미 피트니스(Mi Fitness)(sid=miothealth) 세션을 가져옵니다. auth.json은 자격 증명을 일반 텍스트로 저장합니다. userId와 passToken을 이 브리지(시스템 키체인)에 입력한 후에는 이 파일을 삭제하는 것이 좋습니다.

참고:

  • passToken은 만료됩니다. doctor가 인증 실패를 보고하면 위 단계에 따라 다시 가져오세요.

  • 브라우저 방법은 평소 사용하는 네트워크 환경에서 로그인하세요. 잦거나 원격 위치에서의 작업은 샤오미 계정 위험 제어(슬라이더/문자 인증)를 트리거할 수 있습니다. 위험 제어가 발생하면 QR 코드 방법을 사용하세요.

  • 쿠키 이름과 로그인 흐름은 2026-08월 테스트를 기반으로 하며 계정 지역, 기기 또는 위험 제어 정책에 따라 다를 수 있습니다. 샤오미는 또한 비공개 API를 수시로 변경할 수 있습니다(상단의 실험적 고지 참조).

  • 이 두 값은 계정 로그인 상태와 동일하므로 공유하거나 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이 포함되지 않지만 일반 텍스트 user_id와 같은 식별 열이 포함됩니다. 내보내기 파일은 민감한 개인 데이터이므로 안전하게 보관하세요. 내보낸 건강 기록은 기본적으로 Git에서 무시됩니다.

내보내기 형식(JSON 봉투 구조, CSV 레이아웃, 닫힌 구간 날짜 필터링 규칙)은 내보내기 형식을 참조하세요.

MCP 서비스

호환 명령 사용 가능:

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

사용 가능한 도구로는 연결 상태, 동기화, 적용 범위, 일일 요약, 신체 측정, 수면, 운동, 심박수, 혈중 산소 포화도(SpO2) 및 스트레스 쿼리와 에이전트 지향 workout_series 시계열 도구가 있습니다. max_points 상한에 따라 자동으로 다운샘플링(고정 시간 버킷 평균, SQLite 내 집계)하고 응답에 downsampled, source_points, returned_points, method를 정직하게 표시하며 전체 정밀도 통계(평균/최소/최대/백분위수)와 심박수 구간 시간을 제공합니다. query_workouts, get_daily_summary와 같은 목록/요약 도구에는 data_quality(적용 일수, 누락된 지표, 마지막 동기화 시간)가 함께 제공됩니다.

클라이언트 통합 예시(Claude Code / Codex와 같은 MCP 클라이언트용 구성 JSON):

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

참고: serve는 HTTP 서비스가 아니라 표준 입력/출력을 통해 클라이언트와 통신하는 stdio 서비스입니다. 터미널에서 직접 실행하면 "멈춘" 것처럼 보이지만, 이는 MCP 클라이언트의 메시지를 기다리는 정상적인 동작입니다. 일상적으로는 위 구성대로 MCP 클라이언트가 시작하도록 하세요.

Python 종속성으로 사용

정규화된 어댑터는 호환 모듈 이름으로 계속 사용할 수 있습니다:

from mi_fitness_mcp.adapters.mi_fitness_cloud import MiFitnessCloudAdapter

다운스트림 프로젝트는 커넥터 소스를 vendor하거나 복사하는 대신 이 패키지를 설치해야 합니다.

라이선스

라이선스 변경 이력: 2026-08-03 이전에 릴리스된 버전은 MIT 라이선스(업스트림 kubulashvili/mi-fitness-mcp 및 binglua/mi-fitness-mcp-cn의 MIT 귀속은 LICENSE 상단의 NOTICE 섹션에 유지됨)를 따릅니다. 현재 버전의 새로운 코드는 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 — 로컬 우선 Garmin 데이터 MCP 서비스. 이 프로젝트와 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