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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ cached session, so it also overrides a stale cached timezone.
|------|-------------|
| `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, optionally at a given time of day |
| `update_food_entry` | Change a logged entry's amount or measure, or move it to another diary group |
| `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 Down
94 changes: 93 additions & 1 deletion src/cronometer_api_mcp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,8 @@ class CronometerClient:
dispatches on worker threads. Auth state transitions are serialized (see
`_auth_lock`), edits to a given custom food are serialized per food id
(see `_food_lock`), and macro split reads/writes share `_macro_split_lock`.
Macro target updates share `_macro_targets_lock`.
Macro target updates share `_macro_targets_lock`, and diary serving edits
are serialized per serving id (see `_serving_lock`).
"""

def __init__(self, *, session_path: Path | None = None) -> None:
Expand All @@ -216,6 +217,8 @@ def __init__(self, *, session_path: Path | None = None) -> None:
# entire object. `_food_locks_guard` protects the lock registry.
self._food_locks: dict[int, threading.Lock] = {}
self._food_locks_guard = threading.Lock()
self._serving_locks: dict[str, threading.Lock] = {}
self._serving_locks_guard = threading.Lock()
self._macro_targets_lock = threading.Lock()
self._macro_split_lock = threading.Lock()

Expand Down Expand Up @@ -1670,6 +1673,95 @@ def add_serving(
)
return data

def _serving_lock(self, serving_id: str | int) -> threading.Lock:
"""Serialize the fetch-modify-save cycle for one diary serving."""
key = str(serving_id)
with self._serving_locks_guard:
lock = self._serving_locks.get(key)
if lock is None:
lock = self._serving_locks[key] = threading.Lock()
return lock

def update_serving(
self,
serving_id: str | int,
day: date | None = None,
*,
grams: float | None = None,
measure_id: int | None = None,
diary_group: int | None = None,
) -> dict:
"""Change the amount, measure or meal group of a logged serving.

Fetches the day's diary, takes the serving as stored and sends it back
to /api/v2/edit_serving with the changed fields. The server keeps the
serving id. The meal group lives in the high bits of `order` (see
add_serving); a moved serving goes to the end of its new group. The
app moves entries with /api/v2/update_order, but edit_serving accepts
a new `order` as well (verified against the live API), so one call
covers both.

Args:
serving_id: The servingId from get_diary.
day: The day the serving is logged on. Defaults to today.
grams: New weight in grams. Requires a weight-based food or recipe;
serving-based recipes store reference-serving counts instead.
measure_id: New display measure (grams stays the amount).
diary_group: New meal group number, as resolve_diary_group
returns it for one of the account's enabled groups.

Returns the updated serving as sent.
"""
if grams is None and measure_id is None and diary_group is None:
raise ValueError("update_serving needs grams, measure_id or diary_group")
if grams is not None and grams <= 0:
raise ValueError(f"grams must be positive, got {grams}")
# Group numbers come from the account's layout (resolve_diary_group);
# they occupy the high 16 bits of `order`.
if diary_group is not None and not 0 <= diary_group <= 0xFFFF:
raise ValueError(f"diary_group must be 0-65535, got {diary_group}")

with self._serving_lock(serving_id):
entries = self.get_diary(day).get("diary", [])
serving = next(
(e for e in entries if str(e.get("servingId")) == str(serving_id)),
None,
)
if serving is None:
raise CronometerError(
f"No serving {serving_id} in the diary for {self._format_day(day)}"
)

serving = dict(serving)
if grams is not None:
food = self.get_food(serving["foodId"])
if any(m.get("type") == "Recipe" for m in food.get("measures") or []):
raise CronometerError(
f"Serving {serving_id} is a serving-based recipe; grams updates "
"require a weight-based food or recipe. Change this amount "
"in Cronometer instead."
)
serving["grams"] = grams
if measure_id is not None:
serving["measureId"] = measure_id
if diary_group is not None and serving.get("order", 0) >> 16 != diary_group:
last = max(
(
e.get("order", 0) & 0xFFFF
for e in entries
if e.get("order", 0) >> 16 == diary_group
),
default=0,
)
serving["order"] = (diary_group << 16) | (last + 1)

payload = {"serving": serving, "config": {"call_version": 2}}
data = self._request("/api/v2/edit_serving", payload)
if str(data.get("id")) != str(serving["servingId"]):
raise CronometerError(f"Failed to update serving {serving_id}: {data}")
logger.info("Updated serving %s on %s", serving_id, serving.get("day"))
return serving

# ------------------------------------------------------------------
# Diary: notes
# ------------------------------------------------------------------
Expand Down
45 changes: 45 additions & 0 deletions src/cronometer_api_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,51 @@ def add_food_entry(
return _err(e)


@mcp.tool(annotations=_WRITE_IDEMPOTENT)
def update_food_entry(
entry_id: str,
date: str | None = None,
grams: float | None = None,
measure_id: int | None = None,
diary_group: str | None = None,
) -> str:
"""Change a logged food entry: its amount, its measure, or its meal.

Use get_food_log to find the entry ID. Pass only what should change.

Args:
entry_id: Serving/entry ID from get_food_log.
date: Date the entry is logged on as YYYY-MM-DD (defaults to today).
grams: New weight of the serving in grams. Only supported for weight-based
foods and recipes; change serving-based recipe amounts in Cronometer.
measure_id: New measure/unit ID from get_food_details (the amount is
still given in grams).
diary_group: Move to another meal: the name of one of the account's
enabled diary groups (see get_diary_groups), matched ignoring case
and whitespace. "auto" is not accepted here.
"""
try:
client = _get_client()
group = None
if diary_group is not None:
group = client.resolve_diary_group(diary_group)
if group["group"] is None:
raise ValueError(
'diary_group "auto" cannot move an entry; name the target '
"group (see get_diary_groups)."
)
entry = client.update_serving(
entry_id,
_parse_date(date),
grams=grams,
measure_id=measure_id,
diary_group=group["group"] if group else None,
)
return _ok({"entry": entry, **(_group_echo(group) if group else {})})
except Exception as e:
return _err(e)


@mcp.tool(annotations=_DESTRUCTIVE)
def remove_food_entry(
entry_ids: list[str],
Expand Down
Loading
Loading