Skip to main content
Glama

fitbit-mcp

CI License: GPL v3 Python 3.13+

MCP-сервер для Fitbit Web API с поддержкой OAuth PKCE, локальным кэшем SQLite и анализом трендов.

Разработан для Claude Code и других клиентов MCP. Синхронизирует ваши данные Fitbit с локальной базой данных для быстрых офлайн-запросов — после начальной синхронизации вызовы API не требуются.

Возможности

  • OAuth 2.0 PKCE — безопасный процесс аутентификации, секрет клиента не требуется

  • Локальный кэш SQLite — синхронизируйте один раз, запрашивайте мгновенно

  • Инкрементальная синхронизация — загружает только новые данные с момента последней синхронизации

  • 9 инструментов MCP — синхронизация, запросы (7 типов данных) и анализ трендов

  • Live-режим — обход кэша и прямой запрос к API

  • CLI — настройка аутентификации, синхронизация и импорт JSON из командной строки

  • Обработка ограничений скорости — автоматический повтор при получении ответов 429

Related MCP server: Fitbit MCP

Типы данных

Инструмент

Данные

fitbit_get_heart_rate

ЧСС в покое, зоны ЧСС

fitbit_get_activity

Шаги, калории, активные минуты, расстояние

fitbit_get_exercises

Тренировки (название, длительность, ЧСС, калории)

fitbit_get_sleep

Длительность, эффективность, фазы сна

fitbit_get_weight

Вес, ИМТ, % жира в организме

fitbit_get_spo2

Насыщение крови кислородом (ср./мин./макс.)

fitbit_get_hrv

Вариабельность сердечного ритма (RMSSD)

fitbit_trends

Агрегированные средние значения (недельные/месячные/квартальные)

Требования

Настройка

1. Установка

pip install .

Или для разработки:

pip install -e ".[dev]"

2. Регистрация приложения Fitbit

  1. Перейдите на dev.fitbit.com/apps и создайте новое приложение

  2. Установите OAuth 2.0 Application Type в значение Personal

  3. Установите Redirect URL на http://localhost:8080

  4. Запишите свой Client ID (секрет клиента не понадобится — PKCE его не использует)

3. Аутентификация

fitbit-mcp auth

Это откроет браузер для входа в Fitbit, обменяет код авторизации через PKCE и сохранит токены локально.

Токены хранятся в ~/.config/fitbit-mcp/fitbit_tokens.json с правами доступа 0600. Токены доступа истекают через 8 часов и обновляются автоматически. Токены обновления истекают после 90 дней неактивности.

4. Регистрация в Claude Code

claude mcp add -s user fitbit -- fitbit-mcp

5. Первая синхронизация (опционально)

Инструменты запроса автоматически синхронизируются при первом использовании, поэтому этот шаг можно пропустить. Чтобы предварительно заполнить кэш или синхронизировать более длинную историю, выполните:

fitbit-mcp sync --days 30

Использование CLI

fitbit-mcp              Start the MCP server (stdio transport)
fitbit-mcp auth         Interactive OAuth setup
fitbit-mcp sync         Sync data to local cache
  --days N              Days of history for first sync (default: 30)
  --types TYPE,...      Data types to sync (default: all)
fitbit-mcp import       Import existing JSON data files
  --data-dir PATH       Directory containing JSON files

Справочник инструментов MCP

Инструменты запроса автоматически синхронизируются при первом запросе каждого дня для каждого типа данных. Используйте live=True, чтобы полностью обойти кэш и получить данные напрямую из API.

Все инструменты запроса принимают следующие общие параметры:

  • start_date — дата начала в формате YYYY-MM-DD, YYYY-MM или 30d (относительно). По умолчанию: последние 30 дней.

  • end_date — дата окончания в формате YYYY-MM-DD. По умолчанию: сегодня.

  • live — если true, данные берутся из API Fitbit, а не из кэша (обходит автосинхронизацию).

fitbit_get_exercises также принимает:

  • exercise_type — фильтр по названию активности (регистронезависимое совпадение подстроки), например, "cycling", "walk", "run". По умолчанию: все типы.

fitbit_sync

Синхронизирует данные из API Fitbit в локальный кэш SQLite. Инструменты запроса вызывают это автоматически при первом использовании в день, поэтому явные вызовы нужны только для более длинной истории или принудительного обновления.

  • data_types — что синхронизировать: all, heart_rate, activity, exercises, sleep, weight, spo2, hrv. Через запятую. По умолчанию: all.

  • days — количество дней истории для первой синхронизации (по умолчанию: 30). Последующие синхронизации являются инкрементальными.

fitbit_trends

Анализ агрегированных трендов на основе кэшированных данных.

  • data_type — что анализировать: heart_rate, activity, exercises, sleep, weight, spo2, hrv. По умолчанию: activity.

  • period — агрегация: weekly, monthly, quarterly. По умолчанию: monthly.

  • start_date — дата начала. По умолчанию: последние 12 месяцев (365 дней).

  • end_date — дата окончания. По умолчанию: сегодня.

  • compare — сравнение двух периодов: last_30d vs previous_30d, 2026-03 vs 2026-02, 2026-Q1 vs 2025-Q4. Если задано, period/start_date/end_date игнорируются.

Области доступа (OAuth scopes)

Во время настройки запрашиваются следующие области доступа API Fitbit:

Область

Доступные данные

activity

Шаги, калории, активные минуты, расстояние

heartrate

ЧСС в покое и зоны ЧСС

sleep

Длительность и фазы сна

weight

Вес, ИМТ, % жира в организме

oxygen_saturation

SpO2 (кислород в крови)

profile

Профиль пользователя (ID, отображаемое имя)

Это минимальные области, необходимые для всех 9 инструментов. Если вам нужен только подмножество, вы можете отредактировать FITBIT_SCOPES в config.py перед настройкой.

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

Пути можно переопределить через переменные окружения:

Переменная

По умолчанию

Описание

FITBIT_MCP_CONFIG_DIR

~/.config/fitbit-mcp/

Директория для учетных данных OAuth

FITBIT_MCP_DB_PATH

~/.local/share/fitbit-mcp/fitbit.db

Путь к базе данных SQLite

Ограничения скорости

API Fitbit разрешает 150 запросов в час. Инструмент синхронизации автоматически обрабатывает ограничения скорости, но имейте в виду:

  • Синхронизация активности использует 1 вызов API в день (конечная точка для диапазона дат отсутствует)

  • Начальная синхронизация за 30 дней использует около 30 из вашей квоты 150/час

  • ЧСС, сон, вес, SpO2 и HRV используют конечные точки с диапазоном дат и работают гораздо эффективнее

Используйте live=False (по умолчанию), чтобы запрашивать данные из кэша и полностью избегать вызовов API.

Безопасность данных

Этот проект включает pre-commit хук (scripts/check-no-data.sh), который предотвращает случайную фиксацию:

  • Файлов базы данных (*.db, *.db-journal, *.db-wal)

  • Конфигураций/учетных данных (config/*.json)

  • Больших файлов (>100 КБ)

Установите его после клонирования:

cp scripts/check-no-data.sh .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit

Импорт существующих данных

Если у вас есть существующие данные Fitbit в виде JSON-файлов (например, из предыдущего экспорта или скрипта), вы можете импортировать их массово:

fitbit-mcp import --data-dir /path/to/json/files/

Ожидаемые имена файлов: heart_rate.json, activity.json, exercises.json, sleep.json, weight.json, spo2.json, hrv.json. См. src/fitbit_mcp/importer.py для ознакомления с ожидаемым форматом JSON.

Участие в разработке

См. CONTRIBUTING.md для настройки разработки, рабочего процесса тестирования и pre-commit хука. Изменения отслеживаются в CHANGELOG.md.

Лицензия

GPL-3.0-or-later

Available Tools

18 tools
fitbit_get_activityA

Get daily activity summaries (steps, calories, active minutes, distance).

Returns data from the local cache by default. Use live=True to fetch from Fitbit API. Run fitbit_sync first to populate the cache.

Note: live=True fetches one API call per day - avoid large ranges to stay within the 150 requests/hour rate limit.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. live: If true, fetch directly from Fitbit API instead of cache.

Returns one entry per day with steps, calories, active minutes, distance. active_minutes = very_active + fairly_active (excludes lightly active).

Inputs: live, end_date, start_date. Returns: result

fitbit_get_azmA

Get daily Active Zone Minutes (AZM) - Fitbit's headline cardio metric.

AZM counts minutes spent in heart rate zones at or above Fat Burn intensity. Cardio and Peak zone minutes count double. Returns from local cache by default, auto-syncing if stale. Use live=True to bypass the cache.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. live: If true, fetch directly from Fitbit API instead of cache.

Returns one entry per day with total_minutes plus per-zone breakdown (fat_burn_minutes, cardio_minutes, peak_minutes). Distinct from active_minutes in fitbit_get_activity, which counts wall-clock minutes regardless of intensity.

Inputs: live, end_date, start_date. Returns: result

fitbit_get_breathing_rateA

Get nightly breathing rate (avg breaths per minute during sleep).

Sourced during sleep tracking. Useful as an illness/recovery signal: sustained increases of 2-3 bpm above personal baseline can indicate incipient infection or strain. Returns from cache by default, auto-syncing if stale.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. live: If true, fetch directly from Fitbit API instead of cache.

Returns one entry per night with breaths_per_min. Typical adult range: 12-20 bpm at rest.

Inputs: live, end_date, start_date. Returns: result

fitbit_get_cardio_fitnessA

Get Cardio Fitness Score (VO2 Max estimate).

Fitbit estimates VO2 Max from resting HR, HR during walks/runs, and demographics. Updates roughly weekly. Returns from cache by default, auto-syncing if stale.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. live: If true, fetch directly from Fitbit API instead of cache.

Returns entries with vo2_max_low and vo2_max_high (mL/kg/min). Fitbit reports as a range (e.g. 39-43); when a single value is given, low and high are equal. Higher = better cardiorespiratory fitness.

Inputs: live, end_date, start_date. Returns: result

fitbit_get_core_temperatureA

Get manually-logged core (body) temperature readings (degrees Celsius).

These are absolute body temperatures the user enters by hand - e.g. a forehead/thermometer reading saved to Fitbit - and are the right source for fever / body-temperature questions. They are NOT the device-derived nightly skin-temperature variation from fitbit_get_skin_temperature. A single day can hold several readings (each timestamped), useful for tracking a fever over time.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. live: If true, fetch directly from Fitbit API instead of cache.

Returns one entry per logged reading with datetime (YYYY-MM-DDThh:mm:ss) and temp_celsius.

Inputs: live, end_date, start_date. Returns: result

fitbit_get_devicesA

List paired Fitbit devices with battery level and last sync time.

Live-only (no caching) - reflects current device state. Useful for monitoring tracker health, knowing which device produced data, and spotting sync gaps.

Returns one entry per paired device with id, type, device_version, battery (e.g. "High"), battery_level (0-100), last_sync_time, mac, and features list.

Inputs: no named parameters. Returns: result

fitbit_get_exercisesA

Get exercise log entries (individual tracked activities).

Returns exercise sessions from the local cache by default. Use live=True to fetch from Fitbit API. Run fitbit_sync first to populate the cache.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. exercise_type: Filter by activity name (case-insensitive substring match), e.g. "cycling", "walk", "run". Default: all types. live: If true, fetch directly from Fitbit API instead of cache.

Returns exercise entries with name, duration, calories, avg heart rate, distance, and source (auto-detect vs manual). Note: HR data from cycling may be unreliable (optical sensor vs handlebar grip).

Inputs: live, end_date, start_date, exercise_type. Returns: result

fitbit_get_food_logA

Get daily food and water log summary.

Returns calories consumed and water intake (in mL) per day. Only populated if the user logs food/water in the Fitbit app. Returns from cache by default, auto-syncing if stale.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. live: If true, fetch directly from Fitbit API. Uses one API call per day.

Returns one entry per day with calories_in and water_ml. Days with no logging are omitted.

Inputs: live, end_date, start_date. Returns: result

fitbit_get_goalsA

Get user-set activity goals for steps, distance, calories, etc.

Live-only (no caching). Use to compare actuals (from fitbit_get_activity) against the targets the user set in the Fitbit app.

Args: period: "daily" or "weekly". Default: "daily".

Returns goals dict with keys like steps, distance, calories_out, active_minutes, active_zone_minutes, floors. Weekly omits some fields.

Inputs: period. Returns: result

fitbit_get_heart_rateA

Get daily resting heart rate and heart rate zones.

Returns resting HR and zone breakdown (Out of Range, Fat Burn, Cardio, Peak) from the local cache by default, auto-syncing if stale. Use live=True to bypass the cache entirely.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. live: If true, fetch directly from Fitbit API instead of cache.

Returns one entry per day with resting_hr and zones array. Zone data: name, minutes, caloriesOut, max/min HR for each zone.

Inputs: live, end_date, start_date. Returns: result

fitbit_get_hrvA

Get nightly HRV (heart rate variability) data.

Returns data from the local cache by default. Use live=True to fetch from Fitbit API. Run fitbit_sync first to populate the cache.

HRV data is sparse: only nights with on-wrist sleep tracking produce readings. Requires Fitbit Premium for access to this endpoint.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. live: If true, fetch directly from Fitbit API instead of cache.

Returns one entry per night with daily_rmssd and deep_rmssd (ms). RMSSD = root mean square of successive RR interval differences. Higher values generally indicate better recovery and parasympathetic activity.

Inputs: live, end_date, start_date. Returns: result

fitbit_get_lifetime_statsA

Get all-time activity totals and personal best records.

Live-only (no caching). Returns lifetime totals (steps, distance, floors, calories, active score) and personal bests (best day for steps, distance, floors), each with the date the record was set.

Useful for long-term context that the daily activity table can't easily answer (e.g. "what's my best step day ever?").

Inputs: no named parameters. Returns: result

fitbit_get_skin_temperatureA

Get nightly skin temperature variation (degrees Celsius from personal baseline).

This is the device-derived RELATIVE deviation recorded during sleep, NOT an absolute body temperature - for fever / body-temperature readings use fitbit_get_core_temperature instead. Fitbit needs ~3 nights to establish a baseline before values appear. Useful as an illness/cycle/recovery signal.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. live: If true, fetch directly from Fitbit API instead of cache.

Returns one entry per night with nightly_relative (degrees C, can be negative) and log_type (e.g. "dermal").

Inputs: live, end_date, start_date. Returns: result

fitbit_get_sleepA

Get nightly sleep data (duration, stages, efficiency).

Returns sleep data from the local cache by default. Use live=True to fetch from Fitbit API. Run fitbit_sync first to populate the cache.

Sleep data is sparse: only nights with watch-tracked sleep are present. Travel, off-wrist nights, or manual logs may be missing.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. live: If true, fetch directly from Fitbit API instead of cache.

Returns one entry per night with total_minutes, efficiency, start/end times, and stage breakdown (deep, light, REM, wake minutes).

Inputs: live, end_date, start_date. Returns: result

fitbit_get_spo2A

Get nightly SpO2 (blood oxygen saturation) data.

Returns data from the local cache by default. Use live=True to fetch from Fitbit API. Run fitbit_sync first to populate the cache.

SpO2 data is sparse: only nights with on-wrist sleep tracking produce readings. Requires Fitbit Premium for access to this endpoint.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. live: If true, fetch directly from Fitbit API instead of cache.

Returns one entry per night with avg, min, max SpO2 percentage. Normal range: 95-100%. Below 90% may indicate sleep apnea.

Inputs: live, end_date, start_date. Returns: result

fitbit_get_weightA

Get weight log entries (weight, BMI, body fat percentage).

Returns data from the local cache by default. Use live=True to fetch from Fitbit API. Run fitbit_sync first to populate the cache.

Weight data is sparse: only days with weigh-in entries are present.

Args: start_date: Start date as "YYYY-MM-DD", "YYYY-MM", or "30d". Default: last 30 days. end_date: End date as "YYYY-MM-DD". Default: today. live: If true, fetch directly from Fitbit API instead of cache.

Returns one entry per weigh-in with weight_kg, bmi, fat_pct.

Inputs: live, end_date, start_date. Returns: result

fitbit_syncA

Sync Fitbit health data to the local cache.

Fetches data from the Fitbit API and stores it in SQLite for fast offline queries. Run this before using other fitbit_get_* tools.

Syncs incrementally: only fetches data newer than the most recent entry in each table. First sync fetches the specified number of days.

Args: data_types: What to sync. Options: "all", "heart_rate", "activity", "exercises", "sleep", "weight", "spo2", "hrv", "azm", "breathing_rate", "skin_temperature", "core_temperature", "cardio_fitness", "food_log". Comma-separated for multiple, e.g. "sleep,hrv". Default: "all". days: Days of history for first sync (default: 30). Ignored on subsequent syncs (uses last synced date). since: Optional "YYYY-MM-DD" backfill date. When set, fetches from this date regardless of what is already cached - use to pull history older than the current cache. Overrides incremental resume and days. until: Optional "YYYY-MM-DD" inclusive end date; requires since. Together they re-fetch and upsert exactly the since..until window - use to repair a gap in the middle of the cache without re-pulling everything from the gap to today.

Returns summary of records synced per data type. Not for querying data - use fitbit_get_heart_rate, fitbit_get_activity, fitbit_get_sleep, etc. instead.

Inputs: days, since, until, data_types. Returns: result

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A4.7/5.0

    Scored across 18 tools

    Disambiguation5/5

    Each tool clearly targets a distinct Fitbit data type (activity, sleep, heart rate, etc.). The only potential confusion between skin and core temperature is explicitly disambiguated in the descriptions, and other similar metrics (e.g., activity vs. AZM vs. exercises) are clearly differentiated.

    Naming Consistency5/5

    All tools follow a consistent `fitbit_<verb>_<noun>` pattern with snake_case throughout. Retrieval tools uniformly use `fitbit_get_*`, and the two non-retrieval tools (`fitbit_sync`, `fitbit_trends`) are named with distinct, appropriate actions that do not break the overall pattern.

    Tool Count4/5

    With 18 tools, the server is slightly above the typical 3-15 tool range, but the count is justified by the breadth of Fitbit's health data metrics. Each tool serves a unique, non-redundant purpose, so the set feels comprehensive rather than bloated.

    Completeness5/5

    The tool set provides broad coverage of Fitbit's data ecosystem, including activity, sleep, heart rate, HRV, SpO2, breathing, temperature, weight, food, exercise, plus device info and goals. No obvious missing operations for a read-only health data retrieval server; the sync tool ensures offline caching is fully supported.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers