#!/usr/bin/env python3 """healthsql: your Apple Health record as a local database that an AI agent can query. healthsql what the database holds: when the iPhone last synced, the views and their columns, example queries, and every metric with its unit and date range. Start here. healthsql query "SELECT ..." rows as JSON, read-only. More than 2000 rows are cut; aggregate or LIMIT. healthsql status one short answer: is the feed alive, and what clears it if it is not healthsql sync read every waiting file from the iPhone now, however long it takes healthsql mcp serve the same two calls to an MCP client over stdio healthsql setup check this computer, build the database, and print how to connect each agent healthsql connect register the MCP server with claude-code, codex, claude-desktop or cursor Something missing or wrong? Write to contact@dkbuilds.co; a person reads it. The iPhone app writes every Health record to its folder in iCloud Drive. Each command here first reads the files that are new, so an answer is as fresh as the phone's last sync. Nothing leaves this computer. Standard library only; Python 3.9 or later. """ import json import os import re import shutil import sqlite3 import subprocess import sys import time import uuid import zlib from datetime import date, datetime from pathlib import Path VERSION = "0.1.0" APP_NAME = "HealthSQL" COMMAND = "healthsql" CONTAINER = "iCloud~dkbuilds~HealthSQL" # the iPhone app's iCloud Drive folder SITE = "https://healthsql.app" FEEDBACK = "contact@dkbuilds.co" # a person reads it HOME = Path.home() def default_export_dir(): if sys.platform == "win32": # iCloud for Windows keeps app folders beside iCloud Drive return HOME / "iCloudDrive" / CONTAINER / "Documents" return HOME / "Library/Mobile Documents" / CONTAINER / "Documents" def default_db(): if sys.platform == "darwin": return HOME / "Library/Application Support" / APP_NAME / "health.db" base = os.environ.get("LOCALAPPDATA") or os.environ.get("XDG_DATA_HOME") or HOME / ".local/share" return Path(base) / COMMAND / "health.db" EXPORT_DIR = Path(os.environ.get("HEALTHSQL_EXPORT_DIR") or default_export_dir()) # written by the iPhone app HEALTH_DB = Path(os.environ.get("HEALTHSQL_DB") or default_db()) # built here; safe to delete FEED_QUIET_DAYS = 3 MAX_ROWS = 2000 AGENT_BUDGET = 45 # seconds a query gives to new files; the rest waits for the next call SCHEMA_VERSION = 1 # raise it after a change to the tables; the database is then rebuilt from the files SCHEMA = """ CREATE TABLE IF NOT EXISTS types (type_id INTEGER PRIMARY KEY, type TEXT UNIQUE NOT NULL, metric TEXT NOT NULL); CREATE INDEX IF NOT EXISTS types_metric ON types (metric); CREATE TABLE IF NOT EXISTS units (unit_id INTEGER PRIMARY KEY, unit TEXT UNIQUE NOT NULL); CREATE TABLE IF NOT EXISTS sources (source_id INTEGER PRIMARY KEY, source TEXT NOT NULL, name TEXT NOT NULL, device TEXT NOT NULL, UNIQUE (source, name, device)); CREATE TABLE IF NOT EXISTS records ( id BLOB PRIMARY KEY, kind TEXT NOT NULL, type_id INTEGER NOT NULL, start_ts REAL, end_ts REAL, value REAL, unit_id INTEGER, source_id INTEGER, data TEXT) WITHOUT ROWID; CREATE INDEX IF NOT EXISTS records_type_start ON records (type_id, start_ts); CREATE TABLE IF NOT EXISTS day_totals ( type_id INTEGER NOT NULL, day TEXT NOT NULL, stat TEXT NOT NULL, value REAL NOT NULL, low REAL, high REAL, unit_id INTEGER, PRIMARY KEY (type_id, day)) WITHOUT ROWID; CREATE INDEX IF NOT EXISTS day_totals_day ON day_totals (day); CREATE TABLE IF NOT EXISTS deleted (id BLOB PRIMARY KEY) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS files (name TEXT PRIMARY KEY, size INTEGER); CREATE VIEW IF NOT EXISTS days AS SELECT t.metric, d.day, d.stat, d.value, d.low AS min, d.high AS max, u.unit FROM day_totals d JOIN types t USING (type_id) LEFT JOIN units u USING (unit_id); CREATE VIEW IF NOT EXISTS samples AS SELECT t.metric, date(r.start_ts, 'unixepoch', 'localtime') AS day, datetime(r.start_ts, 'unixepoch', 'localtime') AS start_local, datetime(r.end_ts, 'unixepoch', 'localtime') AS end_local, r.value, u.unit, s.source, s.name AS source_name, r.data, r.start_ts, r.end_ts FROM records r JOIN types t USING (type_id) LEFT JOIN units u USING (unit_id) LEFT JOIN sources s USING (source_id) WHERE r.kind IN ('q', 'c'); CREATE VIEW IF NOT EXISTS workouts AS SELECT date(r.start_ts, 'unixepoch', 'localtime') AS day, datetime(r.start_ts, 'unixepoch', 'localtime') AS start_local, json_extract(r.data, '$.activity') AS activity, round(json_extract(r.data, '$.duration') / 60.0, 1) AS minutes, round(coalesce(json_extract(r.data, '$.stats.HKQuantityTypeIdentifierDistanceWalkingRunning.sum'), json_extract(r.data, '$.stats.HKQuantityTypeIdentifierDistanceCycling.sum'), json_extract(r.data, '$.stats.HKQuantityTypeIdentifierDistanceSwimming.sum'))) AS meters, round(json_extract(r.data, '$.stats.HKQuantityTypeIdentifierHeartRate.avg')) AS avg_hr, round(json_extract(r.data, '$.stats.HKQuantityTypeIdentifierHeartRate.max')) AS max_hr, round(json_extract(r.data, '$.stats.HKQuantityTypeIdentifierActiveEnergyBurned.sum')) AS kcal, s.source, s.name AS source_name, r.data, r.start_ts, r.end_ts FROM records r LEFT JOIN sources s USING (source_id) WHERE r.type_id = (SELECT type_id FROM types WHERE type = 'HKWorkoutTypeIdentifier'); CREATE VIEW IF NOT EXISTS sleep AS SELECT date(r.start_ts + 21600, 'unixepoch', 'localtime') AS night, CASE CAST(r.value AS INTEGER) WHEN 0 THEN 'in_bed' WHEN 1 THEN 'asleep' WHEN 2 THEN 'awake' WHEN 3 THEN 'core' WHEN 4 THEN 'deep' WHEN 5 THEN 'rem' END AS stage, round((r.end_ts - r.start_ts) / 60.0, 1) AS minutes, datetime(r.start_ts, 'unixepoch', 'localtime') AS start_local, datetime(r.end_ts, 'unixepoch', 'localtime') AS end_local, s.source, s.name AS source_name, r.start_ts, r.end_ts FROM records r LEFT JOIN sources s USING (source_id) WHERE r.type_id = (SELECT type_id FROM types WHERE type = 'HKCategoryTypeIdentifierSleepAnalysis'); CREATE VIEW IF NOT EXISTS nights_by_source AS SELECT night, source, source_name, round(sum(CASE WHEN stage IN ('asleep', 'core', 'deep', 'rem') THEN minutes END)) AS asleep_min, round(sum(CASE WHEN stage = 'deep' THEN minutes END)) AS deep_min, round(sum(CASE WHEN stage = 'rem' THEN minutes END)) AS rem_min, round(sum(CASE WHEN stage = 'core' THEN minutes END)) AS core_min, round(sum(CASE WHEN stage = 'awake' THEN minutes END)) AS awake_min, round(sum(CASE WHEN stage = 'in_bed' THEN minutes END)) AS in_bed_min, min(CASE WHEN stage IN ('asleep', 'core', 'deep', 'rem') THEN start_local END) AS fell_asleep, max(CASE WHEN stage IN ('asleep', 'core', 'deep', 'rem') THEN end_local END) AS woke FROM sleep GROUP BY night, source, source_name; CREATE VIEW IF NOT EXISTS nights AS SELECT night, asleep_min, deep_min, rem_min, core_min, awake_min, in_bed_min, fell_asleep, woke, source, source_name FROM (SELECT *, row_number() OVER (PARTITION BY night ORDER BY (deep_min IS NOT NULL OR rem_min IS NOT NULL) DESC, asleep_min DESC) AS pick FROM nights_by_source WHERE asleep_min > 0) WHERE pick = 1; CREATE VIEW IF NOT EXISTS rings AS SELECT json_extract(data, '$.day') AS day, json_extract(data, '$.moveKcal') AS move_kcal, json_extract(data, '$.moveGoalKcal') AS move_goal_kcal, json_extract(data, '$.exerciseMin') AS exercise_min, json_extract(data, '$.exerciseGoalMin') AS exercise_goal_min, json_extract(data, '$.standHours') AS stand_hours, json_extract(data, '$.standGoalHours') AS stand_goal_hours FROM records WHERE type_id = (SELECT type_id FROM types WHERE type = 'HKActivitySummary'); """ # The columns of `daily`: one row for each day, Health's own total for the measures people ask about most. DAILY = [ ("steps", "StepCount", "value"), ("distance_m", "DistanceWalkingRunning", "value"), ("flights", "FlightsClimbed", "value"), ("active_kcal", "ActiveEnergyBurned", "value"), ("basal_kcal", "BasalEnergyBurned", "value"), ("exercise_min", "AppleExerciseTime", "value"), ("stand_min", "AppleStandTime", "value"), ("daylight_min", "TimeInDaylight", "value"), ("resting_hr", "RestingHeartRate", "value"), ("hrv_ms", "HeartRateVariabilitySDNN", "value"), ("hr_avg", "HeartRate", "value"), ("hr_min", "HeartRate", "low"), ("hr_max", "HeartRate", "high"), ("walking_hr", "WalkingHeartRateAverage", "value"), ("respiratory_rate", "RespiratoryRate", "value"), ("spo2", "OxygenSaturation", "value"), ("vo2max", "VO2Max", "value"), ("wrist_temp_c", "AppleSleepingWristTemperature", "value"), ("weight_kg", "BodyMass", "value"), ("body_fat", "BodyFatPercentage", "value"), ] SCHEMA += "CREATE VIEW IF NOT EXISTS daily AS\n SELECT d.day,\n%s,\n" % ",\n".join( " round(max(CASE WHEN t.metric = '%s' THEN d.%s END), 2) AS %s" % (metric, column, name) for name, metric, column in DAILY ) + """ n.asleep_min, n.deep_min, n.rem_min, n.awake_min, n.fell_asleep, n.woke, n.source_name AS sleep_source FROM day_totals d JOIN types t USING (type_id) LEFT JOIN nights n ON n.night = d.day GROUP BY d.day; """ VIEWS = { "daily": "START HERE for any question about a day or a trend. One row for each day. Every number is Apple" " Health's own total for that day, the number the Health app shows: when the Watch, the iPhone and a" " ring all recorded the same steps, Health counts them once. Sleep columns come from `nights`; night N" " is the night that ends on the morning of day N. spo2 and body_fat are 0-1 fractions.", "days": "Health's own total for each metric and day, for every metric (the list is below). stat says what value" " is: 'sum' for a metric that adds up (steps, energy), 'avg' for one that does not (heart rate), with" " min and max. Use this, never a sum over `samples`, for a daily number.", "nights": "One row for each night of sleep, from one source (the one with sleep stages; if two have stages, the" " longer). `nights_by_source` has the same columns for every source that recorded the night.", "nights_by_source": "One row for each night and each source that recorded it. Use it to compare a watch with a" " ring, or to pick a source other than the one `nights` chose.", "sleep": "One row for each sleep stage interval, from every source. night is the day the person woke; an" " interval that starts at 18:00 or later belongs to the next day's night. Two sources that recorded the" " same night both appear: filter by source_name before you add minutes.", "workouts": "One row for each workout. A ring or another app can write its own copy of a workout the Watch" " recorded: check source_name before you count. data is the whole record: stats for every measure," " events, metadata.", "samples": "One row for each raw measurement or logged event, from every source. For a value at a time of day," " or one source's own numbers. NEVER sum it for a daily total: sources overlap, so use `days`. Always" " filter by metric; there are millions of rows. Units never depend on the phone's settings: lengths" " are m, body mass kg, energy kcal, temperature degC, and a percent is a 0-1 fraction. data holds metadata" " (m), and for a sample that holds many values n, min, max and series ([time, value]).", "rings": "One row for each day of Activity rings, with the goals.", "records": "The table under the views above, with every raw record: kind is q quantity, c category, w workout, route" " (data.points: [time, lat, lon, altitude, speed, accuracy]), mind, ecg, rings. Join types, units and" " sources by their ids.", } EXAMPLES = [ "SELECT day, steps, active_kcal, resting_hr, hrv_ms, asleep_min FROM daily ORDER BY day DESC LIMIT 14", "SELECT strftime('%Y-%W', day) AS week, round(avg(steps)) AS steps, round(avg(resting_hr), 1) AS resting_hr, round(avg(asleep_min)) AS asleep_min FROM daily WHERE day >= date('now', '-90 day') GROUP BY week", "SELECT night, asleep_min, deep_min, rem_min, fell_asleep, woke, source_name FROM nights ORDER BY night DESC LIMIT 7", "SELECT day, activity, minutes, meters, avg_hr, source_name FROM workouts ORDER BY start_ts DESC LIMIT 10", "SELECT day, round(value, 1) AS vo2max FROM days WHERE metric = 'VO2Max' ORDER BY day DESC LIMIT 30", "SELECT strftime('%H', start_local) AS hour, round(avg(value)) AS heart_rate FROM samples WHERE metric = 'HeartRate' AND start_ts >= unixepoch('now', '-1 day') GROUP BY hour", ] COLUMN_KEYS = {"k", "t", "id", "s", "e", "v", "u", "src", "srcName", "dev"} def open_db(path=None, readonly=False): path = Path(path or HEALTH_DB) if readonly: return sqlite3.connect("file:%s?mode=ro" % path, uri=True, timeout=30) path.parent.mkdir(parents=True, exist_ok=True) db = sqlite3.connect(str(path), timeout=30) version = db.execute("PRAGMA user_version").fetchone()[0] if version != SCHEMA_VERSION and db.execute("SELECT count(*) FROM sqlite_master").fetchone()[0]: db.close() # tables from an earlier version: the files in iCloud Drive are the record, so build again for suffix in ("", "-journal", "-wal", "-shm"): if os.path.exists(str(path) + suffix): os.remove(str(path) + suffix) db = sqlite3.connect(str(path), timeout=30) db.execute("PRAGMA journal_mode = WAL") db.execute("PRAGMA synchronous = NORMAL") db.execute("PRAGMA cache_size = -200000") db.executescript(SCHEMA) db.execute("PRAGMA user_version = %d" % SCHEMA_VERSION) return db def record_id(text): """A Health id is a UUID: 16 bytes instead of 36 characters, in a table of millions of rows.""" try: return uuid.UUID(text).bytes except ValueError: return text.encode("utf-8") def metric_name(health_type): return re.sub(r"^HK(QuantityTypeIdentifier|CategoryTypeIdentifier|DataTypeIdentifier)?|TypeIdentifier$", "", health_type) class Ingest: """Writes the lines of one file into the database. Reading a file twice changes nothing: a record replaces the record with the same id, and a deleted id stays deleted even when its record arrives later.""" def __init__(self, db): self.db = db self.types = dict(db.execute("SELECT type, type_id FROM types")) self.units = dict(db.execute("SELECT unit, unit_id FROM units")) self.sources = {(s, n, d): i for i, s, n, d in db.execute("SELECT source_id, source, name, device FROM sources")} self.deleted = {row[0] for row in db.execute("SELECT id FROM deleted")} def key(self, cache, value, sql, args): if value not in cache: cache[value] = self.db.execute(sql, args).lastrowid return cache[value] def file(self, name, size, lines): rows, gone, day_ops, totals = [], [], [], 0 for line in lines: r = json.loads(line) kind, t = r["k"], r.get("t", "") if kind == "del": rid = record_id(r["id"]) gone.append((rid,)) self.deleted.add(rid) continue type_id = self.key(self.types, t, "INSERT INTO types (type, metric) VALUES (?, ?)", (t, metric_name(t))) unit = "fraction (0-1)" if r.get("u") == "%" else r.get("u") # Health's "%" holds 0.97 for 97 percent unit_id = self.key(self.units, unit, "INSERT INTO units (unit) VALUES (?)", (unit,)) if unit else None if kind == "days": # the totals of this type in the range are replaced by the `day` lines that follow day_ops.append(("DELETE FROM day_totals WHERE type_id = ? AND day BETWEEN ? AND ?", (type_id, r["from"], r["to"]))) continue if kind == "day": # Health's total for one day stat = "sum" if "sum" in r else "avg" if isinstance(r.get(stat), (int, float)): day_ops.append(("INSERT OR REPLACE INTO day_totals VALUES (?, ?, ?, ?, ?, ?, ?)", (type_id, r["day"], stat, r[stat], r.get("min"), r.get("max"), unit_id))) totals += 1 continue rid = record_id(r["id"]) if rid in self.deleted: continue source = (r.get("src") or "", r.get("srcName") or "", r.get("dev") or "") source_id = self.key(self.sources, source, "INSERT INTO sources (source, name, device) VALUES (?, ?, ?)", source) if kind in ("q", "c"): # the columns hold a plain sample; keep only what they do not rest = {k: v for k, v in r.items() if k not in COLUMN_KEYS} data = json.dumps(rest, separators=(",", ":")) if rest else None else: data = line value = r.get("v") if isinstance(r.get("v"), (int, float)) else None rows.append((rid, kind, type_id, r.get("s"), r.get("e"), value, unit_id, source_id, data)) with self.db: self.db.executemany("INSERT OR REPLACE INTO records VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", rows) self.db.executemany("INSERT OR IGNORE INTO deleted VALUES (?)", gone) self.db.executemany("DELETE FROM records WHERE id = ?", gone) for sql, args in day_ops: # in the order of the file: a range, then its days self.db.execute(sql, args) self.db.execute("INSERT OR REPLACE INTO files VALUES (?, ?)", (name, size)) return len(rows) + totals def icloud(action, files): """Ask iCloud Drive to download or evict files. It works in the background; nothing here waits for it.""" if sys.platform != "darwin": return for f in files: try: subprocess.run(["/usr/bin/brctl", action, str(f)], capture_output=True, timeout=5) except (OSError, subprocess.SubprocessError): return def lock_file(path): """One process reads the iPhone's files at a time. Returns the open lock, or None when another holds it.""" handle = open(str(path) + ".lock", "w") try: if sys.platform == "win32": import msvcrt msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1) else: import fcntl fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) return handle except OSError: handle.close() return None def sync(folder=None, db_path=None, budget=None, progress=None): """Read the iPhone's files that are new or have grown into the database. A file holds JSON lines, deflated. With a budget in seconds, reading stops when the time is used and the next call continues, so a query never waits on a large backlog. A file that is still in iCloud is asked for and left for a later call. """ folder = Path(folder or EXPORT_DIR) db_path = Path(db_path or HEALTH_DB) in_icloud_drive = "Mobile Documents" in str(folder) db = open_db(db_path) seen = dict(db.execute("SELECT name, size FROM files")) chunks = folder / "v1" todo, cloud = [], [] try: listed = sorted(chunks.glob("*.jsonl.deflate")) if chunks.is_dir() else [] waiting = len(list(chunks.glob(".*.icloud"))) if listed or chunks.is_dir() else 0 except PermissionError: # macOS asks before a program may read iCloud Drive db.close() return {"phone_synced": None, "pending_files": 0, "unread_files": 0, "phone_errors": {}, "problem": "This program may not read iCloud Drive. Allow it in System Settings, Privacy & Security, Files and" " Folders (or Full Disk Access), for the app that runs this command. Then run it again."} for f in listed: try: st = f.stat() except OSError: continue if seen.get(f.name) == st.st_size: continue (cloud if getattr(st, "st_blocks", 1) == 0 and st.st_size > 0 else todo).append(f) unread = len(cloud) + waiting if cloud and in_icloud_drive: icloud("download", cloud[:40]) pending = len(todo) lock = lock_file(db_path) if todo else None if todo and not lock: todo = [] # another process is reading the files now deadline = time.monotonic() + budget if budget else None ingest = Ingest(db) if todo else None today = date.today().isoformat() for index, f in enumerate(todo): if deadline and index and time.monotonic() > deadline: # each call reads at least one file break try: size = f.stat().st_size lines = zlib.decompress(f.read_bytes(), -15).decode("utf-8").splitlines() except (OSError, zlib.error): unread += 1 # half written, or iCloud took it back pending -= 1 continue count = ingest.file(f.name, size, lines) pending -= 1 if progress: progress(f.name, count, pending) if in_icloud_drive and f.name[:10] < today: icloud("evict", [f]) # an earlier day's file never changes; the copy on this computer is not needed again if lock: lock.close() files_read = db.execute("SELECT count(*) FROM files").fetchone()[0] db.close() try: phone = json.loads((folder / "status.json").read_text(encoding="utf-8")) except (OSError, ValueError): phone = {} synced = phone.get("last_sync") feed = { "phone_synced": datetime.fromtimestamp(synced).astimezone().isoformat(timespec="seconds") if synced else None, "pending_files": pending, "unread_files": unread, "phone_errors": phone.get("errors") or {}, } if phone.get("limited_since"): # the person shares only part of their history with the app since = date.fromtimestamp(phone["limited_since"]).isoformat() feed["record_starts"] = since feed["partial_record"] = ("The iPhone shares Health data only from %s on, so older records are not here. To share" " all of it: on the iPhone, Settings, Health, Data Access & Devices, %s." % (since, APP_NAME)) feed["problem"] = problem(folder, feed, synced, files_read) return feed def problem(folder, feed, synced, files_read): """What is wrong with the feed, and the one act that clears it. None when all is well.""" if not folder.is_dir(): return ("No export folder at %s. Install %s on the iPhone, open it and allow Health access. This computer" " must be signed in to the same Apple Account, with iCloud Drive on; the folder then appears by" " itself, in about a minute." % (folder, APP_NAME)) if not synced and not files_read and not feed["unread_files"] and not feed["pending_files"]: return "The iPhone has not exported yet. Open %s on the iPhone and keep it open until the first export ends." % APP_NAME if feed["pending_files"]: return "%d files from the iPhone are not in the database yet. Run `healthsql sync`." % feed["pending_files"] if feed["unread_files"]: return "%d files are still downloading from iCloud Drive. Ask again in a minute." % feed["unread_files"] if synced and time.time() - synced > FEED_QUIET_DAYS * 86400: return ("The iPhone last synced %d days ago. Open %s on the iPhone; it can only read Health while the" " phone is unlocked." % ((time.time() - synced) // 86400, APP_NAME)) return None def overview(): feed = sync(budget=AGENT_BUDGET) db = open_db(readonly=True) views = {name: {"what": what, "columns": [c[1] for c in db.execute("PRAGMA table_info(%s)" % name)]} for name, what in VIEWS.items()} metrics = [{"metric": m, "days": n, "stat": stat, "unit": u, "first": a, "last": b} for m, n, stat, u, a, b in db.execute( "SELECT t.metric, count(*), max(d.stat), max(u.unit), min(d.day), max(d.day)" " FROM day_totals d JOIN types t USING (type_id) LEFT JOIN units u USING (unit_id) GROUP BY t.metric ORDER BY count(*) DESC")] logged = [{"metric": m, "kind": k, "count": n, "first": a, "last": b} for m, k, n, a, b in db.execute( "SELECT t.metric, c.kind, c.n, date(c.first, 'unixepoch', 'localtime'), date(c.last, 'unixepoch', 'localtime')" " FROM (SELECT type_id, kind, count(*) AS n, min(start_ts) AS first, max(start_ts) AS last FROM records" " WHERE kind != 'q' GROUP BY type_id) c JOIN types t USING (type_id) ORDER BY c.n DESC")] db.close() return {"query": 'healthsql query "SELECT ..."', "dialect": "SQLite, read-only", "database": str(HEALTH_DB), **feed, "views": views, "examples": EXAMPLES, "metrics_with_daily_totals": metrics, "other_records": logged} def run_sql(query): feed = sync(budget=AGENT_BUDGET) db = open_db(readonly=True) try: cursor = db.execute(query) names = [c[0] for c in cursor.description or []] def plain(v): if isinstance(v, bytes): return str(uuid.UUID(bytes=v)).upper() if len(v) == 16 else v.decode("utf-8", "replace") return v rows = [dict(zip(names, map(plain, r))) for r in cursor.fetchmany(MAX_ROWS + 1)] finally: db.close() out = {"rows": rows[:MAX_ROWS], "truncated": len(rows) > MAX_ROWS, "phone_synced": feed["phone_synced"]} for key in ("problem", "partial_record"): if feed.get(key): out[key] = feed[key] return out def sync_all(): """Read every waiting file, however long it takes, and say what happened.""" done = [0, 0] def progress(name, count, pending): done[0] += 1 done[1] += count print("%s %d records %d files to go" % (name, count, pending), file=sys.stderr) feed = sync(progress=progress) return {"files_read": done[0], "records_read": done[1], **feed} def status(): feed = sync(budget=AGENT_BUDGET) db = open_db(readonly=True) records, days = db.execute("SELECT (SELECT count(*) FROM records), (SELECT count(DISTINCT day) FROM day_totals)").fetchone() db.close() return {"ok": feed["problem"] is None, **feed, "records": records, "days": days, "export_folder": str(EXPORT_DIR), "database": str(HEALTH_DB), "version": VERSION, "feedback": "Something missing or wrong? Write to %s." % FEEDBACK} SQL_HINT = "Run `healthsql` (or the health_overview tool) for the views and their columns." # ---------- MCP ---------- MCP_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") MCP_INSTRUCTIONS = ( "The user's whole Apple Health record, in a local SQLite database that their iPhone keeps current. Call" " health_overview once to learn the views, then health_query with SQL. For any daily number use the `daily`" " or `days` view: they hold Apple Health's own totals. Never sum `samples` for a day; several devices record" " the same steps. Each answer carries phone_synced (how fresh the data is) and, when something is wrong, a" " `problem` line that says what the user must do; tell them. If the data cannot answer what the user needs, or" " something looks wrong, tell them they can write to %s." % FEEDBACK ) MCP_TOOLS = [ { "name": "health_overview", "title": "Apple Health: what is available", "description": "What the user's Apple Health database holds: when their iPhone last synced, each view with" " its columns and when to use it, example queries, and every metric with its unit and date" " range. Call this first, once.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}, "annotations": {"readOnlyHint": True, "openWorldHint": False}, }, { "name": "health_query", "title": "Apple Health: run SQL", "description": "Run one read-only SQLite query on the user's Apple Health database and get rows as JSON (at" " most %d; aggregate or LIMIT). Start from the `daily` view (one row per day: steps, energy," " resting heart rate, HRV, sleep, weight and more), `nights` for sleep, `workouts` for" " training. health_overview lists every view and column." % MAX_ROWS, "inputSchema": { "type": "object", "properties": {"sql": {"type": "string", "description": "One SQLite SELECT statement."}}, "required": ["sql"], "additionalProperties": False, }, "annotations": {"readOnlyHint": True, "openWorldHint": False}, }, ] def mcp_call(name, arguments): if name == "health_overview": return overview() if name == "health_query": return run_sql(str(arguments.get("sql") or "")) raise KeyError(name) def mcp_handle(message): """One JSON-RPC message in, one reply out (None for a notification).""" method, ident = message.get("method"), message.get("id") if ident is None: return None try: if method == "initialize": asked = (message.get("params") or {}).get("protocolVersion") result = {"protocolVersion": asked if asked in MCP_VERSIONS else MCP_VERSIONS[0], "capabilities": {"tools": {}}, "serverInfo": {"name": COMMAND, "title": APP_NAME, "version": VERSION}, "instructions": MCP_INSTRUCTIONS} elif method == "ping": result = {} elif method == "tools/list": result = {"tools": MCP_TOOLS} elif method == "tools/call": params = message.get("params") or {} try: answer = mcp_call(params.get("name"), params.get("arguments") or {}) result = {"content": [{"type": "text", "text": json.dumps(answer, separators=(",", ":"))}]} except KeyError: return {"jsonrpc": "2.0", "id": ident, "error": {"code": -32602, "message": "Unknown tool: %s" % params.get("name")}} except sqlite3.Error as e: # the model can fix its own query, so this is a tool result, not a protocol error result = {"content": [{"type": "text", "text": "%s. %s" % (e, SQL_HINT)}], "isError": True} elif method in ("resources/list", "prompts/list"): result = {method.split("/")[0]: []} else: return {"jsonrpc": "2.0", "id": ident, "error": {"code": -32601, "message": "Method not found: %s" % method}} except Exception as e: # one bad request must not end the server return {"jsonrpc": "2.0", "id": ident, "error": {"code": -32603, "message": str(e)}} return {"jsonrpc": "2.0", "id": ident, "result": result} def mcp_serve(stdin=None, stdout=None): stdin, stdout = stdin or sys.stdin, stdout or sys.stdout for line in stdin: line = line.strip() if not line: continue try: message = json.loads(line) except ValueError: reply = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}} else: reply = mcp_handle(message) if isinstance(message, dict) else None if reply is not None: stdout.write(json.dumps(reply, separators=(",", ":")) + "\n") stdout.flush() # ---------- setup ---------- CLIENTS = ("claude-code", "codex", "claude-desktop", "cursor") def json_config(client): """Where a client that reads a JSON file keeps its MCP servers, or None when the client is not on this computer.""" if client == "cursor": folder = HOME / ".cursor" elif sys.platform == "win32": folder = Path(os.environ.get("APPDATA") or HOME) / "Claude" else: folder = HOME / "Library/Application Support/Claude" name = "mcp.json" if client == "cursor" else "claude_desktop_config.json" return folder / name if folder.is_dir() else None def add_to_json(path, me): """Add this server to a client's file and keep everything else in it. The file as it was is kept beside it.""" entry = {"command": me, "args": ["mcp"]} try: config = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} except ValueError: return "not changed: %s is not valid JSON" % path if not isinstance(config, dict) or not isinstance(config.setdefault("mcpServers", {}), dict): return "not changed: %s has an unexpected shape" % path if config["mcpServers"].get(COMMAND) == entry: return "already connected" if path.exists(): shutil.copy2(str(path), str(path) + ".before-" + COMMAND) config["mcpServers"][COMMAND] = entry path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8") return "connected; restart the app to load it" def add_with_cli(program, args): try: done = subprocess.run([program] + args, capture_output=True, text=True, timeout=60) except (OSError, subprocess.SubprocessError) as e: return "failed: %s" % e said = (done.stderr or done.stdout or "").strip() if done.returncode == 0: return "connected" return "already connected" if "already exists" in said else "failed: %s" % (said.splitlines() or ["no message"])[-1] def connect(names): """Register `healthsql mcp` with the named MCP clients; with no name, say which clients are on this computer.""" me = str(Path(sys.argv[0]).resolve()) found = {"claude-code": shutil.which("claude"), "codex": shutil.which("codex"), "claude-desktop": json_config("claude-desktop"), "cursor": json_config("cursor")} if not names: return {"on_this_computer": [c for c in CLIENTS if found[c]], "connect_one": "%s connect " % COMMAND, "any_other_mcp_client": {"mcpServers": {COMMAND: {"command": me, "args": ["mcp"]}}}} out = {} for name in names: if name not in CLIENTS: out[name] = "unknown client; one of: %s" % ", ".join(CLIENTS) elif not found[name]: out[name] = "not found on this computer" elif name == "claude-code": out[name] = add_with_cli(found[name], ["mcp", "add", "--scope", "user", COMMAND, "--", me, "mcp"]) elif name == "codex": out[name] = add_with_cli(found[name], ["mcp", "add", COMMAND, "--", me, "mcp"]) else: out[name] = add_to_json(found[name], me) return out def setup(wait=120): """Check this computer, build the database, and say how to connect each agent. The first files can take a minute to come down from iCloud Drive, so this waits for them. """ me = str(Path(sys.argv[0]).resolve()) feed = sync_all() deadline = time.monotonic() + wait while (feed["unread_files"] or feed["pending_files"]) and time.monotonic() < deadline: print("Waiting for %d files from iCloud Drive..." % (feed["unread_files"] + feed["pending_files"]), file=sys.stderr) time.sleep(5) feed = sync_all() return { "ok": feed["problem"] is None, "problem": feed["problem"], "phone_synced": feed["phone_synced"], "export_folder": str(EXPORT_DIR), "database": str(HEALTH_DB), "use_it_from_a_shell": "Run `%s` and read its answer; then `%s query \"SELECT ...\"`." % (me, me), "use_it_over_mcp": connect([]), } def main(args=None): args = sys.argv[1:] if args is None else args try: if not args: print(json.dumps(overview(), indent=1)) elif args == ["status"]: out = status() print(json.dumps(out, indent=1)) return 0 if out["ok"] else 1 elif args == ["sync"]: print(json.dumps(sync_all(), indent=1)) elif args == ["mcp"]: mcp_serve() elif args == ["setup"]: out = setup() print(json.dumps(out, indent=1)) return 0 if out["ok"] else 1 elif args[0] == "connect": out = connect(args[1:]) print(json.dumps(out, indent=1)) return 1 if any(str(v).startswith(("failed", "unknown", "not ")) for v in out.values()) else 0 elif len(args) == 2 and args[0] in ("query", "sql"): print(json.dumps(run_sql(args[1]), separators=(",", ":"))) elif args in (["--version"], ["version"]): print(VERSION) else: print(__doc__.strip(), file=sys.stderr) return 0 if args in (["--help"], ["-h"], ["help"]) else 2 except sqlite3.Error as e: print("%s. %s" % (e, SQL_HINT), file=sys.stderr) return 1 return 0 if __name__ == "__main__": sys.exit(main())