Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ cached session, so it also overrides a stale cached timezone.

| Tool | Description |
|------|-------------|
| `get_food_log` | Diary entries for a date, each enriched with food name, source, serving measure/count, that food's per-entry nutrient contribution, and the diary group (meal slot) it sits in, plus an energy_summary (target/consumed/remaining kcal) and a nutrition_summary of consumed totals for every tracked nutrient |
| `get_food_log` | Diary entries for a date, each enriched with food name, source, serving measure/count, that food's per-entry nutrient contribution, and the diary group (meal slot) it sits in, plus an energy_summary (target/consumed/remaining kcal) and a nutrition_summary of consumed totals for every tracked nutrient. `detail="compact"` returns a small object per entry instead of the nutrient arrays, and `food_id` narrows the entries to one food |
| `get_daily_nutrition` | Consumed macro and micronutrient totals for every nutrient tracked in Cronometer |
| `get_nutrition_scores` | Category scores (Vitamins, Minerals, etc.) with per-nutrient consumed amounts and confidence levels |

Expand Down
97 changes: 94 additions & 3 deletions src/cronometer_api_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from datetime import date, time, timedelta
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as _pkg_version
from typing import Annotated
from typing import Annotated, Literal

from mcp.server.mcpserver import MCPServer
from mcp.types import ToolAnnotations
Expand Down Expand Up @@ -193,6 +193,8 @@ def _err(e: Exception) -> str:
def get_food_log(
date: str | None = None,
days: Annotated[int, Field(ge=1, le=31, strict=True)] = 1,
detail: Literal["full", "compact"] = "full",
food_id: int | None = None,
) -> str:
"""Get diary entries for one day or the last N calendar days.

Expand Down Expand Up @@ -220,6 +222,10 @@ def get_food_log(
the entry's order or time. name is null for a group number the account
doesn't define. See get_diary_groups for the full list.

A busy day in "full" detail can be ~170,000 characters, which can exceed
a client's output limit. Use detail="compact" (and/or food_id) to keep the
response small.

Note: the per-entry "nutrients" are each food's individual contribution,
which is distinct from the day-level nutrition_summary aggregate below.

Expand Down Expand Up @@ -248,6 +254,21 @@ def get_food_log(
Defaults to today in the account timezone, resolved at call time.
days: Number of calendar days, 1–31 (default 1). Includes the end date;
days=3 includes today, date='yesterday', days=3 excludes today.
detail: "full" (default) returns every entry as described above.
"compact" replaces each diary entry with a small object
without per-entry nutrient arrays: entry_id (the servingId,
noteId, exerciseId or biometricId that remove_food_entry
takes), type, name, food_id, measure_id, grams, servings,
time, order (raw), diary_group ({group, name}, as above),
kcal, protein_g, carbs_g, fat_g, sodium_mg. Notes also carry
their text. grams is passed through as-is (null stays null;
for serving-based recipes it is a serving count). Values that
cannot be derived are null. energy_summary and
nutrition_summary are unchanged. Applies to each day.
food_id: Only entries for this Cronometer food ID (non-food entries
are excluded). It narrows the diary list only;
energy_summary and nutrition_summary still describe the
whole day. Applies in both detail modes and to each day.

One day returns the usual date/diary/summaries. Multiple days return
start_date, end_date, and a days list of those objects, oldest first.
Expand All @@ -256,7 +277,7 @@ def get_food_log(
resolved_days = _resolve_read_days(date, days)
client = _get_client()
return _read_days_response(
[_food_log_for_day(client, day) for day in resolved_days]
[_food_log_for_day(client, day, detail, food_id) for day in resolved_days]
)
except Exception as e:
return _err(e)
Expand All @@ -283,10 +304,80 @@ def get_diary_groups() -> str:
return _err(e)


def _food_log_for_day(client: CronometerClient, day: date) -> dict:
# Nutrient ids used by compact entries: key -> nutrient id.
_COMPACT_NUTRIENTS = {
"kcal": 208,
"protein_g": 203,
"carbs_g": 205,
"fat_g": 204,
"sodium_mg": 307,
}


def _entry_id(entry: dict):
"""The ID remove_food_entry takes for this entry, whatever its type."""
for key in ("servingId", "noteId", "exerciseId", "biometricId"):
if entry.get(key) is not None:
return entry[key]
return None


def _compact_entry(entry: dict) -> dict:
amounts = {
n.get("id"): n.get("amount")
for n in entry.get("nutrients") or []
if isinstance(n, dict)
}
out = {
"entry_id": _entry_id(entry),
"type": entry.get("type"),
"name": entry.get("name"),
"food_id": entry.get("foodId"),
"measure_id": entry.get("measureId"),
"grams": entry.get("grams"),
"servings": entry.get("servings"),
"time": entry.get("time"),
"order": entry.get("order"),
"diary_group": entry.get("diary_group"),
}
for key, nid in _COMPACT_NUTRIENTS.items():
amount = amounts.get(nid)
out[key] = round(amount, 1) if isinstance(amount, (int, float)) else None
if entry.get("type") == "Note":
out["text"] = entry.get("text")
return out


def _food_log_for_day(
client: CronometerClient,
day: date,
detail: str = "full",
food_id: int | None = None,
) -> dict:
if detail not in ("full", "compact"):
raise ValueError("detail must be 'full' or 'compact'.")
data = client.get_diary(day)
# Filter before enriching so only the kept entries' foods are looked up.
if (
food_id is not None
and isinstance(data, dict)
and isinstance(data.get("diary"), list)
):
data["diary"] = [
e
for e in data["diary"]
if isinstance(e, dict) and e.get("foodId") == food_id
]
data = client.enrich_diary_servings(data)
data = client.label_diary_groups(data)
if (
detail == "compact"
and isinstance(data, dict)
and isinstance(data.get("diary"), list)
):
data["diary"] = [
_compact_entry(e) for e in data["diary"] if isinstance(e, dict)
]

summary = (data or {}).get("summary") or {}
target = (summary.get("macros") or {}).get("energy")
Expand Down
182 changes: 182 additions & 0 deletions tests/test_food_log_compact.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
"""get_food_log detail="compact" and the food_id filter."""

import json
from datetime import date
from unittest.mock import Mock

import pytest

from cronometer_api_mcp import server
from cronometer_api_mcp.client import CronometerClient


def _nutrients(kcal):
# A big profile, so size comparisons are meaningful.
base = [
{"id": 208, "name": "Energy", "amount": kcal, "unit": "kcal"},
{"id": 203, "name": "Protein", "amount": 12.34, "unit": "g"},
{"id": 205, "name": "Carbs", "amount": 45.0, "unit": "g"},
{"id": 204, "name": "Fat", "amount": 6.66, "unit": "g"},
{"id": 307, "name": "Sodium", "amount": 321.0, "unit": "mg"},
]
return base + [
{"id": 1000 + i, "name": f"Nutrient {i}", "amount": i, "unit": "mg"}
for i in range(80)
]


def _diary():
return {
"summary": {"macros": {"energy": 2200}, "consumed": {"total": 1800}},
"diary": [
{
"type": "Serving",
"servingId": "s1",
"foodId": 1,
"measureId": 10,
"grams": 100,
"order": (1 << 16) | 1,
"time": "8:00:00",
"name": "Oats",
"servings": 1.0,
"nutrients": _nutrients(380),
},
{
"type": "Serving",
"servingId": "s2",
"foodId": 2,
"measureId": 20,
"grams": 150,
"order": (3 << 16) | 1,
"time": "19:30:00",
"name": "Pasta",
"servings": 1.5,
"nutrients": _nutrients(520),
},
{
"type": "Serving",
"servingId": "s3",
"foodId": 3,
"measureId": 30,
"grams": None,
"order": (4 << 16) | 2,
"time": "15:00:00",
"name": "Recipe",
"nutrients": _nutrients(210),
},
{"type": "Exercise", "exerciseId": 7, "name": "Run", "order": 0},
],
}


def _label(data):
"""Stand-in for label_diary_groups: names from the group number."""
names = {1: "Breakfast", 3: "Dinner", 4: "Snacks"}
for entry in data["diary"]:
group = entry["order"] >> 16
entry["diary_group"] = {"group": group, "name": names.get(group)}
return data


@pytest.fixture
def client(monkeypatch):
c = Mock(spec=CronometerClient)
c.today.return_value = date(2026, 1, 1)
c.get_diary.side_effect = lambda day: _diary()
c.enrich_diary_servings.side_effect = lambda data: data
c.label_diary_groups.side_effect = _label
c.get_consumed_nutrients.return_value = {"macros": {"energy": 1800}}
monkeypatch.setattr(server, "_client", c)
return c


def _entries(**kw):
return json.loads(server.get_food_log(date="2026-01-01", **kw))["diary"]["diary"]


def test_default_is_full(client):
entries = _entries()
assert len(entries) == 4
assert len(entries[0]["nutrients"]) == 85


def test_compact_fields(client):
entries = _entries(detail="compact")
assert entries[0] == {
"entry_id": "s1",
"type": "Serving",
"name": "Oats",
"food_id": 1,
"measure_id": 10,
"grams": 100,
"servings": 1.0,
"time": "8:00:00",
"order": (1 << 16) | 1,
"diary_group": {"group": 1, "name": "Breakfast"},
"kcal": 380.0,
"protein_g": 12.3,
"carbs_g": 45.0,
"fat_g": 6.7,
"sodium_mg": 321.0,
}
assert entries[2]["grams"] is None and entries[2]["servings"] is None
assert entries[3]["kcal"] is None
assert all("nutrients" not in e for e in entries)


def test_compact_entry_ids_cover_every_entry_type(client):
diary = _diary()
diary["diary"] += [
{"type": "Note", "noteId": 42, "text": "ate late", "order": 1 << 16},
{"type": "Biometric", "biometricId": 9, "order": 0},
]
client.get_diary.side_effect = lambda day: diary
entries = _entries(detail="compact")
assert [e["entry_id"] for e in entries[3:]] == [7, 42, 9]
assert entries[4]["text"] == "ate late"
assert all("text" not in e for e in entries[:4] + entries[5:])


def test_compact_keeps_summaries_and_is_much_smaller(client):
full = server.get_food_log(date="2026-01-01")
compact = server.get_food_log(date="2026-01-01", detail="compact")
assert len(compact) < len(full) / 4
out = json.loads(compact)
assert out["energy_summary"]["remaining_kcal"] == 400
assert out["nutrition_summary"]["macros"]["energy"] == 1800


def test_compact_without_group_labels(client):
"""Group labels are best-effort: an unlabeled diary still compacts."""
client.label_diary_groups.side_effect = lambda data: data
entries = _entries(detail="compact")
assert entries[0]["diary_group"] is None
assert entries[0]["entry_id"] == "s1"


def test_food_id_filter(client):
assert [e["food_id"] for e in _entries(food_id=2, detail="compact")] == [2]
assert [e["servingId"] for e in _entries(food_id=1)] == ["s1"]
assert _entries(food_id=99) == []


def test_food_id_filter_runs_before_enrichment(client):
seen = []
client.enrich_diary_servings.side_effect = lambda data: (
seen.append([e["foodId"] for e in data["diary"]]) or data
)
_entries(food_id=2)
assert seen == [[2]]


def test_invalid_detail_rejected(client):
out = json.loads(server.get_food_log(date="2026-01-01", detail="tiny"))
assert out["status"] == "error"
client.get_diary.assert_not_called()


def test_multi_day_applies_compact_to_each_day(client):
out = json.loads(server.get_food_log(date="2026-01-01", days=2, detail="compact"))
assert [d["date"] for d in out["days"]] == ["2025-12-31", "2026-01-01"]
for d in out["days"]:
assert all("nutrients" not in e for e in d["diary"]["diary"])
Loading