cronometer-api-mcp 0.2.3__tar.gz → 0.2.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/PKG-INFO +26 -1
  2. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/README.md +25 -0
  3. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/pyproject.toml +1 -1
  4. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/server.json +2 -2
  5. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/src/cronometer_api_mcp/client.py +253 -12
  6. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/src/cronometer_api_mcp/server.py +277 -183
  7. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/tests/test_client.py +50 -7
  8. cronometer_api_mcp-0.2.5/tests/test_custom_food_edit.py +513 -0
  9. cronometer_api_mcp-0.2.5/tests/test_relative_dates.py +187 -0
  10. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/tests/test_server_import.py +5 -7
  11. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/uv.lock +33 -33
  12. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/.dockerignore +0 -0
  13. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/.env.example +0 -0
  14. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/.github/dependabot.yml +0 -0
  15. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/.github/workflows/ci.yml +0 -0
  16. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/.github/workflows/docker.yml +0 -0
  17. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/.github/workflows/publish.yml +0 -0
  18. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/.gitignore +0 -0
  19. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/.python-version +0 -0
  20. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/Dockerfile +0 -0
  21. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/LICENSE +0 -0
  22. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/src/cronometer_api_mcp/__init__.py +0 -0
  23. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/tests/test_timezone.py +0 -0
  24. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.5}/tests/test_totp.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cronometer-api-mcp
3
- Version: 0.2.3
3
+ Version: 0.2.5
4
4
  Summary: MCP server for Cronometer nutrition data using the mobile REST API
5
5
  Author: Randy
6
6
  License-Expression: MIT
@@ -155,6 +155,8 @@ cached session, so it also overrides a stale cached timezone.
155
155
  | `add_food_entry` | Log a food serving to the diary |
156
156
  | `remove_food_entry` | Remove one or more diary entries |
157
157
  | `add_custom_food` | Create a custom food with specified nutrition |
158
+ | `update_custom_food` | Edit a custom food in place: name, nutrition, or serving size |
159
+ | `delete_custom_food` | Retire a custom food so it leaves search and the Custom Foods list (existing diary entries are kept) |
158
160
  | `add_recipe` | Create a recipe from existing foods referenced by ID and gram weight |
159
161
  | `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 |
160
162
  | `copy_day` | Copy all entries from the previous day |
@@ -172,6 +174,29 @@ cached session, so it also overrides a stale cached timezone.
172
174
 
173
175
  All date parameters use `YYYY-MM-DD` format and default to today when omitted.
174
176
 
177
+ ### Relative dates and recent days
178
+
179
+ `get_food_log`, `get_daily_nutrition`, and `get_nutrition_scores` also accept
180
+ `"today"`, `"yesterday"`, and `"N days ago"` as their `date`. These are resolved
181
+ at call time using your Cronometer account timezone, so Claude can pass relative
182
+ inputs without relying on dates from earlier in a long conversation.
183
+
184
+ `get_food_log` and `get_daily_nutrition` accept `days` (1–31, default 1), counting
185
+ back from the inclusive end `date`:
186
+
187
+ ```python
188
+ get_food_log(date="yesterday")
189
+ get_nutrition_scores(date="3 days ago")
190
+ get_daily_nutrition(days=3) # Last 3 days, including today
191
+ get_daily_nutrition(date="yesterday", days=3) # Previous 3 complete calendar days
192
+ get_food_log(days=7) # Recent meals, including today
193
+ ```
194
+
195
+ For “my calories the last few days,” use `get_daily_nutrition(days=3)`.
196
+ Single-day responses retain their existing shape. Multi-day responses contain
197
+ `start_date`, `end_date`, and a `days` list of daily results, oldest first.
198
+ Returned dates are always concrete `YYYY-MM-DD` values.
199
+
175
200
  ## Transport
176
201
 
177
202
  stdio only. For remote/hosted use, the stdio server is wrapped by
@@ -135,6 +135,8 @@ cached session, so it also overrides a stale cached timezone.
135
135
  | `add_food_entry` | Log a food serving to the diary |
136
136
  | `remove_food_entry` | Remove one or more diary entries |
137
137
  | `add_custom_food` | Create a custom food with specified nutrition |
138
+ | `update_custom_food` | Edit a custom food in place: name, nutrition, or serving size |
139
+ | `delete_custom_food` | Retire a custom food so it leaves search and the Custom Foods list (existing diary entries are kept) |
138
140
  | `add_recipe` | Create a recipe from existing foods referenced by ID and gram weight |
139
141
  | `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 |
140
142
  | `copy_day` | Copy all entries from the previous day |
@@ -152,6 +154,29 @@ cached session, so it also overrides a stale cached timezone.
152
154
 
153
155
  All date parameters use `YYYY-MM-DD` format and default to today when omitted.
154
156
 
157
+ ### Relative dates and recent days
158
+
159
+ `get_food_log`, `get_daily_nutrition`, and `get_nutrition_scores` also accept
160
+ `"today"`, `"yesterday"`, and `"N days ago"` as their `date`. These are resolved
161
+ at call time using your Cronometer account timezone, so Claude can pass relative
162
+ inputs without relying on dates from earlier in a long conversation.
163
+
164
+ `get_food_log` and `get_daily_nutrition` accept `days` (1–31, default 1), counting
165
+ back from the inclusive end `date`:
166
+
167
+ ```python
168
+ get_food_log(date="yesterday")
169
+ get_nutrition_scores(date="3 days ago")
170
+ get_daily_nutrition(days=3) # Last 3 days, including today
171
+ get_daily_nutrition(date="yesterday", days=3) # Previous 3 complete calendar days
172
+ get_food_log(days=7) # Recent meals, including today
173
+ ```
174
+
175
+ For “my calories the last few days,” use `get_daily_nutrition(days=3)`.
176
+ Single-day responses retain their existing shape. Multi-day responses contain
177
+ `start_date`, `end_date`, and a `days` list of daily results, oldest first.
178
+ Returned dates are always concrete `YYYY-MM-DD` values.
179
+
155
180
  ## Transport
156
181
 
157
182
  stdio only. For remote/hosted use, the stdio server is wrapped by
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "cronometer-api-mcp"
7
- version = "0.2.3"
7
+ version = "0.2.5"
8
8
  description = "MCP server for Cronometer nutrition data using the mobile REST API"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/rwestergren/cronometer-api-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.2.3",
9
+ "version": "0.2.5",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "pypi",
13
13
  "identifier": "cronometer-api-mcp",
14
- "version": "0.2.3",
14
+ "version": "0.2.5",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -10,11 +10,14 @@ endpoints.
10
10
  """
11
11
 
12
12
  import base64
13
+ import copy
13
14
  import hashlib
14
15
  import hmac
15
16
  import json
16
17
  import logging
18
+ import math
17
19
  import os
20
+ import re
18
21
  import struct
19
22
  import threading
20
23
  import time
@@ -81,6 +84,9 @@ _OZ_GRAMS = 28.3495231
81
84
  # Nutrient IDs create_custom_food() already writes via its named macro args
82
85
  # (including the derived/negative-ID duplicates it sends alongside them).
83
86
  # extra_nutrients must not reuse one of these -- see create_custom_food().
87
+ # A serving name that leads with a plain number, e.g. "2 cookies".
88
+ _QUANTITY_LED_NAME = re.compile(r"^\s*(\d+(?:\.\d+)?)\s+(\S.*)$")
89
+
84
90
  _RESERVED_CUSTOM_FOOD_NUTRIENT_IDS = frozenset(
85
91
  {
86
92
  NUTRIENT_IDS["energy"],
@@ -148,8 +154,9 @@ class CronometerClient:
148
154
  Re-authenticates automatically when the session expires.
149
155
 
150
156
  Thread safety: one instance is shared across MCP tool calls, which the SDK
151
- dispatches on worker threads. Only auth state transitions are serialized;
152
- requests still run concurrently. See `_auth_lock`.
157
+ dispatches on worker threads. Auth state transitions are serialized (see
158
+ `_auth_lock`), and edits to a given custom food are serialized per food id
159
+ (see `_food_lock`); everything else runs concurrently.
153
160
  """
154
161
 
155
162
  def __init__(self, *, session_path: Path | None = None) -> None:
@@ -163,6 +170,12 @@ class CronometerClient:
163
170
  # Guards (_user_id, _token, _timezone) and the session file mirroring
164
171
  # them. Reentrant because the auth paths nest: login -> _save_cached_session.
165
172
  self._auth_lock = threading.RLock()
173
+
174
+ # Serialize each food's fetch-modify-save cycle because add_food replaces the
175
+ # entire object. `_food_locks_guard` protects the lock registry.
176
+ self._food_locks: dict[int, threading.Lock] = {}
177
+ self._food_locks_guard = threading.Lock()
178
+
166
179
  # Cache of nutrient definitions (id -> {name, unit, category}).
167
180
  # Definitions are stable for an account, so fetch them once.
168
181
  self._nutrient_defs: dict[int, dict] | None = None
@@ -740,6 +753,224 @@ class CronometerClient:
740
753
  logger.info("Created custom food %r (id=%d)", name, food_id)
741
754
  return {"food_id": food_id, "measure_id": None}
742
755
 
756
+ # ------------------------------------------------------------------
757
+ # Custom food edit / retire
758
+ # ------------------------------------------------------------------
759
+
760
+ def _save_custom_food(self, food: dict) -> dict:
761
+ """Re-send a full food object to /api/v2/add_food, which upserts.
762
+
763
+ A non-zero id edits that food in place (verified against the live API:
764
+ the id, measure ids and unchanged nutrients all survive). The server
765
+ tacks FOOD_CHANGED sync messages onto get_food responses; those are not
766
+ food data and are dropped before sending.
767
+ """
768
+ data = copy.deepcopy(food)
769
+ data.pop("messages", None)
770
+ payload = {"data": data, "config": {"call_version": 1}}
771
+ resp = self._request("/api/v2/add_food", payload)
772
+ if resp.get("id") != data["id"]:
773
+ raise CronometerError(f"Failed to save custom food {data['id']}: {resp}")
774
+ return resp
775
+
776
+ def _food_lock(self, food_id: int) -> threading.Lock:
777
+ """The lock serializing edits of one custom food; see __init__."""
778
+ with self._food_locks_guard:
779
+ lock = self._food_locks.get(food_id)
780
+ if lock is None:
781
+ lock = self._food_locks[food_id] = threading.Lock()
782
+ return lock
783
+
784
+ def _get_custom_food(self, food_id: int) -> dict:
785
+ """Fetch a food and refuse anything that isn't a plain custom food.
786
+
787
+ Re-sending a database food through add_food is untested territory (it
788
+ might create a private copy or fail), so only source "Custom" -- what
789
+ get_food reports for user-created foods -- may be edited or retired.
790
+
791
+ User-created recipes report source "Custom" too, but they carry an
792
+ `ingredients` array their nutrient totals are derived from, and their
793
+ measures follow different rules. Editing one as a plain food would
794
+ leave it inconsistent, so recipes are refused as well.
795
+ """
796
+ food = self.get_food(food_id)
797
+ if food.get("source") != "Custom":
798
+ raise CronometerError(
799
+ f"Food {food_id} ({food.get('name')!r}) is not a custom food "
800
+ f"(source={food.get('source')!r}); only custom foods can be edited"
801
+ )
802
+ if food.get("ingredients"):
803
+ raise CronometerError(
804
+ f"Food {food_id} ({food.get('name')!r}) is a recipe; only plain "
805
+ f"custom foods can be edited or deleted"
806
+ )
807
+ return food
808
+
809
+ @staticmethod
810
+ def _default_measure(food: dict) -> dict | None:
811
+ measures = food.get("measures") or []
812
+ for m in measures:
813
+ if m.get("id") == food.get("defaultMeasureId"):
814
+ return m
815
+ return measures[0] if measures else None
816
+
817
+ def update_custom_food(
818
+ self,
819
+ food_id: int,
820
+ *,
821
+ name: str | None = None,
822
+ calories: float | None = None,
823
+ protein_g: float | None = None,
824
+ fat_g: float | None = None,
825
+ carbs_g: float | None = None,
826
+ fiber_g: float | None = None,
827
+ sugar_g: float | None = None,
828
+ sodium_mg: float | None = None,
829
+ saturated_fat_g: float | None = None,
830
+ extra_nutrients: dict[int, float] | None = None,
831
+ serving_name: str | None = None,
832
+ serving_grams: float | None = None,
833
+ serving_quantity: float | None = None,
834
+ ) -> dict:
835
+ """Edit a user-created custom food in place.
836
+
837
+ Only the fields passed (not None) change; everything else is re-sent
838
+ exactly as the server returned it. Nutrient amounts are per serving --
839
+ the default measure's weight, or serving_grams when given -- and are
840
+ normalized to per-100g like create_custom_food. Changing serving_grams
841
+ alone leaves the stored per-100g values as they are, so the food's
842
+ per-serving numbers shift with the new weight.
843
+
844
+ A measure is `amount` units of `name` weighing `value` grams in total,
845
+ and the app renders the serving as "<amount> <name>". Setting the
846
+ weight therefore also resets the quantity (to serving_quantity, or 1)
847
+ and makes the measure a named ("Atomic") serving. Otherwise a food
848
+ first saved as "400 g" keeps amount=400 and type "Weight" and shows up
849
+ as "400 <serving_name>" with no weight of its own. A quantity leading
850
+ serving_name ("2 cookies") is moved into the quantity for the same
851
+ reason. A quantity set without serving_grams keeps the total weight,
852
+ so the per-unit weight changes.
853
+
854
+ Returns {"food_id": int, "name": str}.
855
+ """
856
+ if extra_nutrients:
857
+ overlap = set(extra_nutrients) & _RESERVED_CUSTOM_FOOD_NUTRIENT_IDS
858
+ if overlap:
859
+ raise ValueError(
860
+ f"extra_nutrients overlaps IDs already set by the named "
861
+ f"macro args: {sorted(overlap)}. Use the named args for "
862
+ f"those instead."
863
+ )
864
+
865
+ # The server splits a leading quantity off a new measure's name
866
+ # ("10 pieces" is stored as amount=10, name="pieces") but not when
867
+ # an existing measure is re-sent, so do the same here. Done before
868
+ # validation so an inferred quantity is checked too.
869
+ quantity_label = "serving_quantity"
870
+ if serving_name is not None:
871
+ led = _QUANTITY_LED_NAME.match(serving_name)
872
+ if led and float(led.group(1)) > 0:
873
+ serving_name = led.group(2)
874
+ if serving_quantity is None:
875
+ serving_quantity = float(led.group(1))
876
+ quantity_label = "serving_name quantity"
877
+
878
+ for label, v in (
879
+ ("serving_grams", serving_grams),
880
+ (quantity_label, serving_quantity),
881
+ ):
882
+ if v is not None and not (math.isfinite(v) and v > 0):
883
+ raise ValueError(f"{label} must be a positive number, got {v!r}")
884
+
885
+ with self._food_lock(food_id):
886
+ food = self._get_custom_food(food_id)
887
+
888
+ if name is not None:
889
+ old_name = food.get("name")
890
+ food["name"] = name
891
+ for t in food.get("translations", []):
892
+ if t.get("name") == old_name:
893
+ t["name"] = name
894
+
895
+ measure = self._default_measure(food)
896
+ if measure is not None:
897
+ if serving_name is not None:
898
+ measure["name"] = serving_name
899
+ if serving_grams is not None:
900
+ measure["value"] = serving_grams
901
+ if serving_grams is not None or serving_quantity is not None:
902
+ measure["amount"] = (
903
+ serving_quantity if serving_quantity is not None else 1.0
904
+ )
905
+ measure["type"] = "Atomic"
906
+ grams = (measure or {}).get("value") or 100.0
907
+ scale = 100.0 / grams if grams > 0 else 1.0
908
+
909
+ per_serving = {
910
+ NUTRIENT_IDS["energy"]: calories,
911
+ NUTRIENT_IDS["protein"]: protein_g,
912
+ NUTRIENT_IDS["fat"]: fat_g,
913
+ NUTRIENT_IDS["carbs"]: carbs_g,
914
+ NUTRIENT_IDS["fiber"]: fiber_g,
915
+ NUTRIENT_IDS["sugar"]: sugar_g,
916
+ NUTRIENT_IDS["sodium"]: sodium_mg,
917
+ NUTRIENT_IDS["saturated_fat"]: saturated_fat_g,
918
+ }
919
+ updates = {
920
+ nid: round(v * scale, 2)
921
+ for nid, v in per_serving.items()
922
+ if v is not None
923
+ }
924
+ for nid, v in (extra_nutrients or {}).items():
925
+ updates[nid] = round(v * scale, 2)
926
+
927
+ nutrients = food.setdefault("nutrients", [])
928
+ by_id = {n["id"]: n for n in nutrients}
929
+
930
+ def set_amount(nid: int, amount: float) -> None:
931
+ entry = by_id.get(nid)
932
+ if entry is None:
933
+ entry = {"id": nid, "amount": amount}
934
+ nutrients.append(entry)
935
+ by_id[nid] = entry
936
+ else:
937
+ entry["amount"] = amount
938
+
939
+ for nid, amount in updates.items():
940
+ set_amount(nid, amount)
941
+
942
+ # Derived duplicates the app stores alongside the macros (see
943
+ # create_custom_food): mirrored protein/fat/carbs and net carbs.
944
+ for src, mirror in ((203, -203), (204, -204), (205, -205)):
945
+ if src in updates:
946
+ set_amount(mirror, updates[src])
947
+ if NUTRIENT_IDS["carbs"] in updates or NUTRIENT_IDS["fiber"] in updates:
948
+ carbs = by_id.get(NUTRIENT_IDS["carbs"], {}).get("amount", 0)
949
+ fiber = by_id.get(NUTRIENT_IDS["fiber"], {}).get("amount", 0)
950
+ set_amount(NUTRIENT_IDS["net_carbs"], round(max(0, carbs - fiber), 2))
951
+
952
+ self._save_custom_food(food)
953
+ logger.info("Updated custom food %r (id=%d)", food["name"], food_id)
954
+ return {"food_id": food_id, "name": food["name"]}
955
+
956
+ def retire_custom_food(self, food_id: int) -> dict:
957
+ """Retire (soft-delete) a user-created custom food.
958
+
959
+ Sets `retired` on the food and saves it. A retired food drops out of
960
+ search and the Custom Foods list but stays readable by id and keeps
961
+ existing diary entries intact. The app's own delete removes the food
962
+ outright through an endpoint this client doesn't know; retiring is the
963
+ closest the known API offers, and it is idempotent.
964
+
965
+ Returns {"food_id": int, "name": str, "retired": True}.
966
+ """
967
+ with self._food_lock(food_id):
968
+ food = self._get_custom_food(food_id)
969
+ food["retired"] = True
970
+ self._save_custom_food(food)
971
+ logger.info("Retired custom food %r (id=%d)", food.get("name"), food_id)
972
+ return {"food_id": food_id, "name": food.get("name"), "retired": True}
973
+
743
974
  # ------------------------------------------------------------------
744
975
  # Recipe creation
745
976
  # ------------------------------------------------------------------
@@ -1452,9 +1683,11 @@ class CronometerClient:
1452
1683
  merges per-entry:
1453
1684
 
1454
1685
  - name, source, category: from the food object
1455
- - measure: {measure_id, name, grams_per_unit} for the entry's
1456
- measureId (falls back to the food's defaultMeasureId)
1457
- - servings: grams / grams_per_unit, when derivable
1686
+ - serving_size: {measure_id, quantity, unit, grams} defining one
1687
+ portion in the entry's measureId (falls back to defaultMeasureId).
1688
+ Recipe measures have null grams: their value is a reference-serving
1689
+ count, not a gram weight.
1690
+ - servings: number of those portions consumed, when derivable
1458
1691
  - nutrients: the food's nutrient profile scaled to the entry's amount
1459
1692
  (per-100g for Weight/Atomic measures, per-serving for Recipe
1460
1693
  measures), labeled with name/unit/category via the nutrient
@@ -1515,18 +1748,26 @@ class CronometerClient:
1515
1748
  )
1516
1749
  grams = entry.get("grams")
1517
1750
  if measure:
1518
- grams_per_unit = measure.get("value")
1519
- entry["measure"] = {
1751
+ portion_value = measure.get("value")
1752
+ quantity = measure.get("amount", 1)
1753
+ if not (
1754
+ isinstance(quantity, (int, float))
1755
+ and math.isfinite(quantity)
1756
+ and quantity > 0
1757
+ ):
1758
+ quantity = None
1759
+ entry["serving_size"] = {
1520
1760
  "measure_id": measure.get("id"),
1521
- "name": measure.get("name"),
1522
- "grams_per_unit": grams_per_unit,
1761
+ "quantity": quantity,
1762
+ "unit": measure.get("name"),
1763
+ "grams": None if measure.get("type") == "Recipe" else portion_value,
1523
1764
  }
1524
1765
  if (
1525
1766
  isinstance(grams, (int, float))
1526
- and isinstance(grams_per_unit, (int, float))
1527
- and grams_per_unit
1767
+ and isinstance(portion_value, (int, float))
1768
+ and portion_value
1528
1769
  ):
1529
- entry["servings"] = round(grams / grams_per_unit, 4)
1770
+ entry["servings"] = round(grams / portion_value, 4)
1530
1771
 
1531
1772
  # Nutrient scaling depends on the measure type:
1532
1773
  # - Recipe measures: nutrients are stored per one reference