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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ cached session, so it also overrides a stale cached timezone.
| Tool | Description |
|------|-------------|
| `get_diary_groups` | The account's diary groups (meal slots) and their names, for interpreting the group in each entry's `order` |
| `add_food_entry` | Log a food serving to the diary |
| `add_food_entry` | Log a food serving to the diary, optionally at a given time of day |
| `remove_food_entry` | Remove one or more diary entries: foods, exercises, notes or biometrics |
| `add_custom_food` | Create a custom food with specified nutrition and optional barcodes |
| `update_custom_food` | Edit a custom food in place: name, nutrition, serving size, or barcodes |
Expand All @@ -144,7 +144,7 @@ cached session, so it also overrides a stale cached timezone.
| `import_recipe` | Create a recipe from a free-text ingredient list; Cronometer matches each line to a database food and converts the amount to grams |
| `copy_day` | Copy all entries from the previous day |
| `mark_day_complete` | Mark a diary day as complete or incomplete |
| `add_note` | Add a note to a diary day |
| `add_note` | Add a note to a diary day, optionally at a given time of day |
| `update_note` | Replace the text of a diary note |

### Targets & Tracking
Expand Down
58 changes: 47 additions & 11 deletions src/cronometer_api_mcp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
import struct
import threading
import time
from datetime import date, datetime
from datetime import date, datetime, timedelta
from datetime import time as dtime
from pathlib import Path
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

Expand Down Expand Up @@ -1609,6 +1610,7 @@ def add_serving(
translation_id: int = 0,
day: date | None = None,
diary_group: int = 0,
at: dtime | None = None,
) -> dict:
"""Log a food serving to the diary.

Expand All @@ -1627,15 +1629,17 @@ def add_serving(
with the default groups. Otherwise the number from
get_diary_groups; resolve_diary_group maps a name to
it.
at: Time of day to stamp the entry with, in the account timezone.
Defaults to now. Also drives the auto meal group.

Returns the serving confirmation dict from the API.
"""
now = self.now()
when = at or self.now().time()
day_str = self._format_day(day)
time_str = f"{now.hour}:{now.minute}:{now.second}"
time_str = f"{when.hour}:{when.minute}:{when.second}"

if diary_group == 0:
diary_group = _meal_group_for_hour(now.hour)
diary_group = _meal_group_for_hour(when.hour)

serving = {
"order": (diary_group << 16) | 1,
Expand Down Expand Up @@ -1672,7 +1676,11 @@ def add_serving(
# ------------------------------------------------------------------

def add_note(
self, text: str, day: date | None = None, diary_group: int = 0
self,
text: str,
day: date | None = None,
diary_group: int = 0,
at: dtime | None = None,
) -> dict:
"""Add a note to a diary day.

Expand All @@ -1681,12 +1689,30 @@ def add_note(
day: Date to add it to. Defaults to today.
diary_group: Meal group number the note sits in, as for
add_serving (0 = auto, by time of day).
at: Time of day to stamp the note with, in the account timezone.
Defaults to now. Also drives the auto meal group.

Returns the stored note: {"noteId", "text", "day", "order", ...}.
Returns the stored note: {"noteId", "text", "day", "time", "order", ...}.
"""
now = self.now()
when = at or now.time()
if diary_group == 0:
diary_group = _meal_group_for_hour(self.now().hour)
return self._save_note(0, text, self._format_day(day), (diary_group << 16) | 1)
diary_group = _meal_group_for_hour(when.hour)
# The UTC offset in force on the note's own date and time, in the
# account's zone (not now's offset: they differ across a DST change).
stamped = datetime.combine(day or now.date(), when, tzinfo=self._tzinfo())
offset = int((stamped.utcoffset() or timedelta(0)).total_seconds() // 60)
extra = {
"time": f"{when.hour:02d}:{when.minute:02d}:{when.second:02d}",
"offset": str(offset),
}
return self._save_note(
0,
text,
self._format_day(day),
(diary_group << 16) | 1,
extra=extra,
)

def update_note(self, note_id: int, text: str, day: date | None = None) -> dict:
"""Replace the text of an existing diary note, keeping its place.
Expand All @@ -1706,7 +1732,11 @@ def update_note(self, note_id: int, text: str, day: date | None = None) -> dict:
raise CronometerError(
f"No note {note_id} in the diary for {self._format_day(day)}"
)
return self._save_note(note["noteId"], text, note["day"], note["order"])
# Send the stored time and offset back so an edit doesn't drop them.
extra = {k: str(note[k]) for k in ("time", "offset") if note.get(k) is not None}
return self._save_note(
note["noteId"], text, note["day"], note["order"], extra=extra
)

def _save_note(
self,
Expand All @@ -1715,6 +1745,7 @@ def _save_note(
day_str: str,
order: int,
*,
extra: dict[str, str] | None = None,
_retried: bool = False,
) -> dict:
"""Create (note_id 0) or overwrite a note via /photoupload.
Expand All @@ -1735,6 +1766,7 @@ def _save_note(
"order": str(order),
"deleteExistingPhoto": "true" if note_id == 0 else "false",
"noteText": text,
**(extra or {}),
}
form = httpx.Request(
"POST", "/", files={k: (None, v) for k, v in fields.items()}
Expand All @@ -1746,7 +1778,9 @@ def _save_note(
)
if resp.status_code in (401, 403) and not _retried:
self._reauthenticate(sent_token)
return self._save_note(note_id, text, day_str, order, _retried=True)
return self._save_note(
note_id, text, day_str, order, extra=extra, _retried=True
)

resp.raise_for_status()
try:
Expand All @@ -1756,7 +1790,9 @@ def _save_note(
if isinstance(data, dict) and data.get("result") in ("FAIL", "FAILURE"):
if not _retried:
self._reauthenticate(sent_token)
return self._save_note(note_id, text, day_str, order, _retried=True)
return self._save_note(
note_id, text, day_str, order, extra=extra, _retried=True
)
raise CronometerError(f"Failed to save note: {data}")
if not isinstance(data, dict) or "noteId" not in data:
raise CronometerError(f"Failed to save note: {data}")
Expand Down
37 changes: 34 additions & 3 deletions src/cronometer_api_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import logging
import re
import threading
from datetime import date, timedelta
from datetime import date, time, timedelta
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as _pkg_version
from typing import Annotated
Expand Down Expand Up @@ -98,6 +98,21 @@ def _parse_date(d: str | None) -> date | None:
return date.fromisoformat(d)


def _parse_time(t: str | None) -> time | None:
"""Parse an optional 24h time-of-day, "HH:MM" or "HH:MM:SS"."""
if t is None:
return None
try:
value = t.strip()
if not re.fullmatch(r"[0-9]{2}:[0-9]{2}(?::[0-9]{2})?", value):
raise ValueError
return time.fromisoformat(value)
except ValueError:
raise ValueError(
f"Invalid time '{t}'. Use 24-hour HH:MM or HH:MM:SS, e.g. '08:30'."
) from None


def _resolve_read_days(d: str | None, days: int = 1) -> list[date]:
if type(days) is not int or not 1 <= days <= 31:
raise ValueError("days must be an integer between 1 and 31.")
Expand Down Expand Up @@ -305,6 +320,7 @@ def add_food_entry(
date: str | None = None,
translation_id: int = 0,
diary_group: str = "auto",
time: str | None = None,
) -> str:
"""Add a food entry to the Cronometer diary.

Expand All @@ -321,18 +337,23 @@ def add_food_entry(
name of one of the account's diary groups, matched
case-insensitively. Group names are customizable; call
get_diary_groups to see them.
time: Time of day to log at, 24-hour HH:MM or HH:MM:SS in the account
timezone (defaults to now). With diary_group "auto", this also
picks the meal slot, so logging lunch late still lands in lunch.
"""
try:
client = _get_client()
group = client.resolve_diary_group(diary_group)
day = _parse_date(date)
at = _parse_time(time)
result = client.add_serving(
food_id=food_id,
measure_id=measure_id,
grams=grams,
translation_id=translation_id,
day=day,
diary_group=group["group"],
at=at,
)
return _ok(
{
Expand Down Expand Up @@ -381,7 +402,12 @@ def remove_food_entry(


@mcp.tool(annotations=_WRITE)
def add_note(text: str, date: str | None = None, diary_group: str = "auto") -> str:
def add_note(
text: str,
date: str | None = None,
diary_group: str = "auto",
time: str | None = None,
) -> str:
"""Add a note to a diary day.

Notes show up in get_food_log's diary as entries of type "Note". Remove
Expand All @@ -393,11 +419,16 @@ def add_note(text: str, date: str | None = None, diary_group: str = "auto") -> s
diary_group: Meal slot the note sits in: "auto" (default, picks by
time of day) or the name of one of the account's diary groups,
matched case-insensitively (see get_diary_groups).
time: Time of day for the note, 24-hour HH:MM or HH:MM:SS in the
account timezone (defaults to now). With diary_group "auto", this
also picks the meal slot.
"""
try:
client = _get_client()
group = client.resolve_diary_group(diary_group)
note = client.add_note(text, _parse_date(date), group["group"])
note = client.add_note(
text, _parse_date(date), group["group"], at=_parse_time(time)
)
return _ok({"note": note, **_group_echo(group)})
except Exception as e:
return _err(e)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_diary_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ def __init__(self):
def resolve_diary_group(self, name):
return {"group": 4, "name": "Dinner"}

def add_note(self, text, day, group):
def add_note(self, text, day, group, at=None):
self.calls.append(("note", group))
return {"noteId": 1}

Expand Down
79 changes: 79 additions & 0 deletions tests/test_entry_time.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""The optional `time` argument of add_food_entry and add_note."""

import datetime as _dt
import json
from unittest.mock import Mock

import pytest

from cronometer_api_mcp import server
from cronometer_api_mcp.client import CronometerClient


@pytest.fixture
def client(monkeypatch):
c = Mock(spec=CronometerClient)
c.resolve_diary_group.return_value = {"group": 0, "name": "auto"}
c.add_serving.return_value = {"id": 1}
c.add_note.return_value = {"noteId": 2}
monkeypatch.setattr(server, "_client", c)
return c


@pytest.mark.parametrize(
("text", "expected"),
[
("00:00", _dt.time(0, 0)),
("08:30", _dt.time(8, 30)),
(" 21:05:09 ", _dt.time(21, 5, 9)),
("23:59:59", _dt.time(23, 59, 59)),
],
)
def test_add_food_entry_passes_time_to_the_client(client, text, expected):
out = json.loads(server.add_food_entry(1, 2, 100.0, time=text))
assert out["status"] == "success"
assert client.add_serving.call_args.kwargs["at"] == expected


def test_add_note_passes_time_to_the_client(client):
out = json.loads(server.add_note("hi", time="12:30"))
assert out["status"] == "success"
assert client.add_note.call_args.kwargs["at"] == _dt.time(12, 30)


def test_time_defaults_to_now(client):
server.add_food_entry(1, 2, 100.0)
server.add_note("hi")
assert client.add_serving.call_args.kwargs["at"] is None
assert client.add_note.call_args.kwargs["at"] is None


@pytest.mark.parametrize(
"bad",
[
"",
"25:00",
"08:60",
"08:30:60",
"noon",
"8",
"08",
"0830",
"T08:30",
"08:30Z",
"08:30+02:00",
"08:30-08:00",
"08:30:00+02:00",
"08:30:00.123",
],
)
def test_invalid_time_is_an_error_and_writes_nothing(client, bad):
for out in (
server.add_food_entry(1, 2, 100.0, time=bad),
server.add_note("hi", time=bad),
):
data = json.loads(out)
assert data["status"] == "error"
assert "Invalid time" in data["message"]
client.add_serving.assert_not_called()
client.add_note.assert_not_called()
Loading
Loading