cronometer-api-mcp 0.2.3__tar.gz → 0.2.4__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.4}/PKG-INFO +26 -1
  2. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/README.md +25 -0
  3. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/pyproject.toml +1 -1
  4. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/server.json +2 -2
  5. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/src/cronometer_api_mcp/client.py +192 -2
  6. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/src/cronometer_api_mcp/server.py +251 -179
  7. cronometer_api_mcp-0.2.4/tests/test_custom_food_edit.py +340 -0
  8. cronometer_api_mcp-0.2.4/tests/test_relative_dates.py +187 -0
  9. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/tests/test_server_import.py +5 -7
  10. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/uv.lock +30 -30
  11. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/.dockerignore +0 -0
  12. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/.env.example +0 -0
  13. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/.github/dependabot.yml +0 -0
  14. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/.github/workflows/ci.yml +0 -0
  15. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/.github/workflows/docker.yml +0 -0
  16. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/.github/workflows/publish.yml +0 -0
  17. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/.gitignore +0 -0
  18. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/.python-version +0 -0
  19. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/Dockerfile +0 -0
  20. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/LICENSE +0 -0
  21. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/src/cronometer_api_mcp/__init__.py +0 -0
  22. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/tests/test_client.py +0 -0
  23. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/tests/test_timezone.py +0 -0
  24. {cronometer_api_mcp-0.2.3 → cronometer_api_mcp-0.2.4}/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.4
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.4"
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.4",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "pypi",
13
13
  "identifier": "cronometer-api-mcp",
14
- "version": "0.2.3",
14
+ "version": "0.2.4",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -10,6 +10,7 @@ endpoints.
10
10
  """
11
11
 
12
12
  import base64
13
+ import copy
13
14
  import hashlib
14
15
  import hmac
15
16
  import json
@@ -148,8 +149,9 @@ class CronometerClient:
148
149
  Re-authenticates automatically when the session expires.
149
150
 
150
151
  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`.
152
+ dispatches on worker threads. Auth state transitions are serialized (see
153
+ `_auth_lock`), and edits to a given custom food are serialized per food id
154
+ (see `_food_lock`); everything else runs concurrently.
153
155
  """
154
156
 
155
157
  def __init__(self, *, session_path: Path | None = None) -> None:
@@ -163,6 +165,12 @@ class CronometerClient:
163
165
  # Guards (_user_id, _token, _timezone) and the session file mirroring
164
166
  # them. Reentrant because the auth paths nest: login -> _save_cached_session.
165
167
  self._auth_lock = threading.RLock()
168
+
169
+ # Serialize each food's fetch-modify-save cycle because add_food replaces the
170
+ # entire object. `_food_locks_guard` protects the lock registry.
171
+ self._food_locks: dict[int, threading.Lock] = {}
172
+ self._food_locks_guard = threading.Lock()
173
+
166
174
  # Cache of nutrient definitions (id -> {name, unit, category}).
167
175
  # Definitions are stable for an account, so fetch them once.
168
176
  self._nutrient_defs: dict[int, dict] | None = None
@@ -740,6 +748,188 @@ class CronometerClient:
740
748
  logger.info("Created custom food %r (id=%d)", name, food_id)
741
749
  return {"food_id": food_id, "measure_id": None}
742
750
 
751
+ # ------------------------------------------------------------------
752
+ # Custom food edit / retire
753
+ # ------------------------------------------------------------------
754
+
755
+ def _save_custom_food(self, food: dict) -> dict:
756
+ """Re-send a full food object to /api/v2/add_food, which upserts.
757
+
758
+ A non-zero id edits that food in place (verified against the live API:
759
+ the id, measure ids and unchanged nutrients all survive). The server
760
+ tacks FOOD_CHANGED sync messages onto get_food responses; those are not
761
+ food data and are dropped before sending.
762
+ """
763
+ data = copy.deepcopy(food)
764
+ data.pop("messages", None)
765
+ payload = {"data": data, "config": {"call_version": 1}}
766
+ resp = self._request("/api/v2/add_food", payload)
767
+ if resp.get("id") != data["id"]:
768
+ raise CronometerError(f"Failed to save custom food {data['id']}: {resp}")
769
+ return resp
770
+
771
+ def _food_lock(self, food_id: int) -> threading.Lock:
772
+ """The lock serializing edits of one custom food; see __init__."""
773
+ with self._food_locks_guard:
774
+ lock = self._food_locks.get(food_id)
775
+ if lock is None:
776
+ lock = self._food_locks[food_id] = threading.Lock()
777
+ return lock
778
+
779
+ def _get_custom_food(self, food_id: int) -> dict:
780
+ """Fetch a food and refuse anything that isn't a plain custom food.
781
+
782
+ Re-sending a database food through add_food is untested territory (it
783
+ might create a private copy or fail), so only source "Custom" -- what
784
+ get_food reports for user-created foods -- may be edited or retired.
785
+
786
+ User-created recipes report source "Custom" too, but they carry an
787
+ `ingredients` array their nutrient totals are derived from, and their
788
+ measures follow different rules. Editing one as a plain food would
789
+ leave it inconsistent, so recipes are refused as well.
790
+ """
791
+ food = self.get_food(food_id)
792
+ if food.get("source") != "Custom":
793
+ raise CronometerError(
794
+ f"Food {food_id} ({food.get('name')!r}) is not a custom food "
795
+ f"(source={food.get('source')!r}); only custom foods can be edited"
796
+ )
797
+ if food.get("ingredients"):
798
+ raise CronometerError(
799
+ f"Food {food_id} ({food.get('name')!r}) is a recipe; only plain "
800
+ f"custom foods can be edited or deleted"
801
+ )
802
+ return food
803
+
804
+ @staticmethod
805
+ def _default_measure(food: dict) -> dict | None:
806
+ measures = food.get("measures") or []
807
+ for m in measures:
808
+ if m.get("id") == food.get("defaultMeasureId"):
809
+ return m
810
+ return measures[0] if measures else None
811
+
812
+ def update_custom_food(
813
+ self,
814
+ food_id: int,
815
+ *,
816
+ name: str | None = None,
817
+ calories: float | None = None,
818
+ protein_g: float | None = None,
819
+ fat_g: float | None = None,
820
+ carbs_g: float | None = None,
821
+ fiber_g: float | None = None,
822
+ sugar_g: float | None = None,
823
+ sodium_mg: float | None = None,
824
+ saturated_fat_g: float | None = None,
825
+ extra_nutrients: dict[int, float] | None = None,
826
+ serving_name: str | None = None,
827
+ serving_grams: float | None = None,
828
+ ) -> dict:
829
+ """Edit a user-created custom food in place.
830
+
831
+ Only the fields passed (not None) change; everything else is re-sent
832
+ exactly as the server returned it. Nutrient amounts are per serving --
833
+ the default measure's weight, or serving_grams when given -- and are
834
+ normalized to per-100g like create_custom_food. Changing serving_grams
835
+ alone leaves the stored per-100g values as they are, so the food's
836
+ per-serving numbers shift with the new weight.
837
+
838
+ Returns {"food_id": int, "name": str}.
839
+ """
840
+ if extra_nutrients:
841
+ overlap = set(extra_nutrients) & _RESERVED_CUSTOM_FOOD_NUTRIENT_IDS
842
+ if overlap:
843
+ raise ValueError(
844
+ f"extra_nutrients overlaps IDs already set by the named "
845
+ f"macro args: {sorted(overlap)}. Use the named args for "
846
+ f"those instead."
847
+ )
848
+
849
+ with self._food_lock(food_id):
850
+ food = self._get_custom_food(food_id)
851
+
852
+ if name is not None:
853
+ old_name = food.get("name")
854
+ food["name"] = name
855
+ for t in food.get("translations", []):
856
+ if t.get("name") == old_name:
857
+ t["name"] = name
858
+
859
+ measure = self._default_measure(food)
860
+ if measure is not None:
861
+ if serving_name is not None:
862
+ measure["name"] = serving_name
863
+ if serving_grams is not None:
864
+ measure["value"] = serving_grams
865
+ grams = (measure or {}).get("value") or 100.0
866
+ scale = 100.0 / grams if grams > 0 else 1.0
867
+
868
+ per_serving = {
869
+ NUTRIENT_IDS["energy"]: calories,
870
+ NUTRIENT_IDS["protein"]: protein_g,
871
+ NUTRIENT_IDS["fat"]: fat_g,
872
+ NUTRIENT_IDS["carbs"]: carbs_g,
873
+ NUTRIENT_IDS["fiber"]: fiber_g,
874
+ NUTRIENT_IDS["sugar"]: sugar_g,
875
+ NUTRIENT_IDS["sodium"]: sodium_mg,
876
+ NUTRIENT_IDS["saturated_fat"]: saturated_fat_g,
877
+ }
878
+ updates = {
879
+ nid: round(v * scale, 2)
880
+ for nid, v in per_serving.items()
881
+ if v is not None
882
+ }
883
+ for nid, v in (extra_nutrients or {}).items():
884
+ updates[nid] = round(v * scale, 2)
885
+
886
+ nutrients = food.setdefault("nutrients", [])
887
+ by_id = {n["id"]: n for n in nutrients}
888
+
889
+ def set_amount(nid: int, amount: float) -> None:
890
+ entry = by_id.get(nid)
891
+ if entry is None:
892
+ entry = {"id": nid, "amount": amount}
893
+ nutrients.append(entry)
894
+ by_id[nid] = entry
895
+ else:
896
+ entry["amount"] = amount
897
+
898
+ for nid, amount in updates.items():
899
+ set_amount(nid, amount)
900
+
901
+ # Derived duplicates the app stores alongside the macros (see
902
+ # create_custom_food): mirrored protein/fat/carbs and net carbs.
903
+ for src, mirror in ((203, -203), (204, -204), (205, -205)):
904
+ if src in updates:
905
+ set_amount(mirror, updates[src])
906
+ if NUTRIENT_IDS["carbs"] in updates or NUTRIENT_IDS["fiber"] in updates:
907
+ carbs = by_id.get(NUTRIENT_IDS["carbs"], {}).get("amount", 0)
908
+ fiber = by_id.get(NUTRIENT_IDS["fiber"], {}).get("amount", 0)
909
+ set_amount(NUTRIENT_IDS["net_carbs"], round(max(0, carbs - fiber), 2))
910
+
911
+ self._save_custom_food(food)
912
+ logger.info("Updated custom food %r (id=%d)", food["name"], food_id)
913
+ return {"food_id": food_id, "name": food["name"]}
914
+
915
+ def retire_custom_food(self, food_id: int) -> dict:
916
+ """Retire (soft-delete) a user-created custom food.
917
+
918
+ Sets `retired` on the food and saves it. A retired food drops out of
919
+ search and the Custom Foods list but stays readable by id and keeps
920
+ existing diary entries intact. The app's own delete removes the food
921
+ outright through an endpoint this client doesn't know; retiring is the
922
+ closest the known API offers, and it is idempotent.
923
+
924
+ Returns {"food_id": int, "name": str, "retired": True}.
925
+ """
926
+ with self._food_lock(food_id):
927
+ food = self._get_custom_food(food_id)
928
+ food["retired"] = True
929
+ self._save_custom_food(food)
930
+ logger.info("Retired custom food %r (id=%d)", food.get("name"), food_id)
931
+ return {"food_id": food_id, "name": food.get("name"), "retired": True}
932
+
743
933
  # ------------------------------------------------------------------
744
934
  # Recipe creation
745
935
  # ------------------------------------------------------------------