cronometer-mcp 2.4.2__tar.gz → 2.4.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.
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/PKG-INFO +2 -2
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/README.md +1 -1
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/RESEARCH-copy-repeat-gwt-rpc.md +1 -1
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/cronometer_mcp/__init__.py +1 -1
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/cronometer_mcp/client.py +149 -182
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/cronometer_mcp/server.py +10 -9
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/pyproject.toml +1 -1
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/server.json +2 -2
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/tests/test_client.py +131 -121
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/tests/test_diary_groups.py +152 -4
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/tests/test_live.py +1 -1
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/.github/workflows/drift.yml +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/.github/workflows/publish.yml +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/.gitignore +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/AGENTS.md +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/CLAUDE.md +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/LICENSE +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/SPEC-diary-groups.md +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/SPEC-streamable-http.md +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/cronometer_mcp/markdown.py +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/release.sh +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/tests/__init__.py +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/tests/test_drift.py +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/tests/test_live_gate.py +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/tests/test_markdown.py +0 -0
- {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.4}/tests/test_server.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: cronometer-mcp
|
|
3
|
-
Version: 2.4.
|
|
3
|
+
Version: 2.4.4
|
|
4
4
|
Summary: MCP server for Cronometer nutrition data — pull food logs, macros, and micronutrients via the Model Context Protocol
|
|
5
5
|
Project-URL: Homepage, https://github.com/cphoskins/cronometer-mcp
|
|
6
6
|
Project-URL: Repository, https://github.com/cphoskins/cronometer-mcp
|
|
@@ -190,7 +190,7 @@ the credentials themselves keep full access.
|
|
|
190
190
|
|------|-------------|
|
|
191
191
|
| `search_foods` | Search the Cronometer food database |
|
|
192
192
|
| `list_diary_groups` | List this account's diary groups and the values `diary_group` accepts |
|
|
193
|
-
| `get_food_details` |
|
|
193
|
+
| `get_food_details` | List a food's serving measures with their gram weights |
|
|
194
194
|
| `add_food_entry` | Add a food entry to the diary |
|
|
195
195
|
| `remove_food_entry` | Remove a food entry from the diary |
|
|
196
196
|
| `copy_day` | Copy all diary entries from one date to another |
|
|
@@ -166,7 +166,7 @@ the credentials themselves keep full access.
|
|
|
166
166
|
|------|-------------|
|
|
167
167
|
| `search_foods` | Search the Cronometer food database |
|
|
168
168
|
| `list_diary_groups` | List this account's diary groups and the values `diary_group` accepts |
|
|
169
|
-
| `get_food_details` |
|
|
169
|
+
| `get_food_details` | List a food's serving measures with their gram weights |
|
|
170
170
|
| `add_food_entry` | Add a food entry to the diary |
|
|
171
171
|
| `remove_food_entry` | Remove a food entry from the diary |
|
|
172
172
|
| `copy_day` | Copy all diary entries from one date to another |
|
|
@@ -363,7 +363,7 @@ Methods captured during session initialization:
|
|
|
363
363
|
- `getAllFood` - full nutrition data for all foods in current diary
|
|
364
364
|
- `getDashboardConfig` - dashboard layout
|
|
365
365
|
- `getBrazeEvents` - analytics events
|
|
366
|
-
- `getFood` - detailed food data for a specific food
|
|
366
|
+
- `getFood` - detailed food data for a specific food (removed by 2026-12-05; now REST `GET /api/v3/food/{id}`)
|
|
367
367
|
- `getCaloriesConsumedAndBurned` - energy balance
|
|
368
368
|
- `getBiometrics` - biometric measurements
|
|
369
369
|
- `getSleepBiometricsByDayAndMetricId` - sleep data
|
|
@@ -15,6 +15,7 @@ import logging
|
|
|
15
15
|
import os
|
|
16
16
|
import pickle
|
|
17
17
|
import re
|
|
18
|
+
from collections import Counter
|
|
18
19
|
from datetime import date
|
|
19
20
|
from pathlib import Path
|
|
20
21
|
|
|
@@ -34,11 +35,14 @@ EXPORT_URL = "https://cronometer.com/export"
|
|
|
34
35
|
# parameter type was removed from Cronometer's serialization policy, so
|
|
35
36
|
# calling it returns IncompatibleRemoteServiceException.
|
|
36
37
|
FOOD_SEARCH_URL = "https://cronometer.com/api/v3/user/{user_id}/food-search/string"
|
|
38
|
+
# Food details moved to REST too (observed 2026-12-05): the getFood RPC is gone
|
|
39
|
+
# from CronometerService and returns IncompatibleRemoteServiceException.
|
|
40
|
+
FOOD_URL = "https://cronometer.com/api/v3/food/{food_source_id}"
|
|
37
41
|
GWT_NOCACHE_JS_URL = "https://cronometer.com/cronometer/cronometer.nocache.js"
|
|
38
42
|
GWT_CACHE_JS_URL = "https://cronometer.com/cronometer/{permutation}.cache.js"
|
|
39
43
|
|
|
40
44
|
# NCCDB "universal" measure_id that works for any food in updateDiary.
|
|
41
|
-
# CRDB foods have food-specific measure_ids in their
|
|
45
|
+
# CRDB foods have food-specific measure_ids in their get_food response,
|
|
42
46
|
# but those IDs cause "ghost entries" (counted but invisible in diary).
|
|
43
47
|
# Using an NCCDB measure_id (here: eggs' "mL chopped" measure) with the
|
|
44
48
|
# correct weight_grams produces working entries for ALL food sources.
|
|
@@ -109,15 +113,6 @@ GWT_REMOVE_SERVING = (
|
|
|
109
113
|
"J|I|{nonce}|1|2|3|4|3|5|6|7|8|{serving_id}|{user_id}|"
|
|
110
114
|
)
|
|
111
115
|
|
|
112
|
-
GWT_GET_FOOD = (
|
|
113
|
-
"7|0|7|https://cronometer.com/cronometer/|"
|
|
114
|
-
"{gwt_header}|"
|
|
115
|
-
"com.cronometer.shared.rpc.CronometerService|"
|
|
116
|
-
"getFood|java.lang.String/2004016611|"
|
|
117
|
-
"I|{nonce}|"
|
|
118
|
-
"1|2|3|4|2|5|6|7|{food_source_id}|"
|
|
119
|
-
)
|
|
120
|
-
|
|
121
116
|
GWT_GET_ALL_MACRO_SCHEDULES = (
|
|
122
117
|
"7|0|7|https://cronometer.com/cronometer/|"
|
|
123
118
|
"{gwt_header}|"
|
|
@@ -360,6 +355,14 @@ class SessionExpiredError(RuntimeError):
|
|
|
360
355
|
"""Cronometer rejected the session (expired or logged out server-side)."""
|
|
361
356
|
|
|
362
357
|
|
|
358
|
+
class DiaryGroupsUnreadable(RuntimeError):
|
|
359
|
+
"""The response carries diary group settings that could not be parsed.
|
|
360
|
+
|
|
361
|
+
Distinct from an account with no group settings: falling back to the
|
|
362
|
+
default meals here could enable a disabled group or rename one.
|
|
363
|
+
"""
|
|
364
|
+
|
|
365
|
+
|
|
363
366
|
class _GwtReader:
|
|
364
367
|
"""Read a GWT-RPC //OK response object by object, the way GWT does.
|
|
365
368
|
|
|
@@ -596,7 +599,13 @@ class CronometerClient:
|
|
|
596
599
|
|
|
597
600
|
# The settings map in this same response carries the user's diary
|
|
598
601
|
# groups. Parse it here so the fresh-login path costs no extra call.
|
|
599
|
-
|
|
602
|
+
# Unreadable groups must not fail the login: leave them unfetched so
|
|
603
|
+
# diary_groups re-fetches and raises on first use.
|
|
604
|
+
try:
|
|
605
|
+
self._diary_groups = self._parse_diary_groups(resp.text)
|
|
606
|
+
except DiaryGroupsUnreadable:
|
|
607
|
+
logger.warning("Diary group settings unreadable", exc_info=True)
|
|
608
|
+
self._diary_groups = None
|
|
600
609
|
|
|
601
610
|
# Update nonce from cookies
|
|
602
611
|
new_nonce = self._cookie_value("sesnonce")
|
|
@@ -1052,25 +1061,43 @@ class CronometerClient:
|
|
|
1052
1061
|
Unlike the old RPC, this returns both ids, so a follow-up get_food()
|
|
1053
1062
|
call is no longer needed just to resolve food_id.
|
|
1054
1063
|
"""
|
|
1064
|
+
self.authenticate() # sets user_id, which the URL needs
|
|
1065
|
+
hits = self._rest_get_json(
|
|
1066
|
+
FOOD_SEARCH_URL.format(user_id=self.user_id),
|
|
1067
|
+
params={
|
|
1068
|
+
"query": query.upper(),
|
|
1069
|
+
"maxResults": max_results,
|
|
1070
|
+
"sources": "All",
|
|
1071
|
+
"categoryId": 0,
|
|
1072
|
+
"selectedTab": "ALL",
|
|
1073
|
+
"type": "All",
|
|
1074
|
+
},
|
|
1075
|
+
)
|
|
1076
|
+
return [self._map_search_hit(hit) for hit in hits]
|
|
1077
|
+
|
|
1078
|
+
def _rest_get_json(self, url: str, params: dict | None = None):
|
|
1079
|
+
"""GET a cookie-authenticated REST endpoint and return its JSON.
|
|
1080
|
+
|
|
1081
|
+
Logs in again once on 401/403 or on a 200 that is not JSON (an
|
|
1082
|
+
expired session can land on the login page after a redirect).
|
|
1083
|
+
"""
|
|
1055
1084
|
self.authenticate()
|
|
1056
1085
|
for attempt in range(2):
|
|
1057
|
-
resp = self.session.get(
|
|
1058
|
-
FOOD_SEARCH_URL.format(user_id=self.user_id),
|
|
1059
|
-
params={
|
|
1060
|
-
"query": query.upper(),
|
|
1061
|
-
"maxResults": max_results,
|
|
1062
|
-
"sources": "All",
|
|
1063
|
-
"categoryId": 0,
|
|
1064
|
-
"selectedTab": "ALL",
|
|
1065
|
-
"type": "All",
|
|
1066
|
-
},
|
|
1067
|
-
timeout=REQUEST_TIMEOUT,
|
|
1068
|
-
)
|
|
1086
|
+
resp = self.session.get(url, params=params, timeout=REQUEST_TIMEOUT)
|
|
1069
1087
|
if resp.status_code in (401, 403) and not attempt:
|
|
1070
1088
|
self._reauthenticate()
|
|
1071
1089
|
continue
|
|
1072
1090
|
resp.raise_for_status()
|
|
1073
|
-
|
|
1091
|
+
try:
|
|
1092
|
+
return resp.json()
|
|
1093
|
+
except ValueError:
|
|
1094
|
+
if not attempt:
|
|
1095
|
+
self._reauthenticate()
|
|
1096
|
+
continue
|
|
1097
|
+
raise RuntimeError(
|
|
1098
|
+
f"Cronometer response from {url} is not JSON, even after "
|
|
1099
|
+
f"logging in again (landed on {getattr(resp, 'url', url)})."
|
|
1100
|
+
) from None
|
|
1074
1101
|
|
|
1075
1102
|
@staticmethod
|
|
1076
1103
|
def _map_search_hit(hit: dict) -> dict:
|
|
@@ -1102,8 +1129,8 @@ class CronometerClient:
|
|
|
1102
1129
|
|
|
1103
1130
|
Cronometer Gold exposes 8 diary group slots. They arrive as settings
|
|
1104
1131
|
keys ``DG01``-``DG08`` (display names) alongside ``DG01ON``-``DG08ON``
|
|
1105
|
-
(enable flags), inside the settings map the authenticate call
|
|
1106
|
-
returns.
|
|
1132
|
+
(optional enable flags), inside the settings map the authenticate call
|
|
1133
|
+
returns. An omitted enable flag leaves the named slot enabled.
|
|
1107
1134
|
|
|
1108
1135
|
The wire ``diary_group`` value used by updateDiary is **0-based** over
|
|
1109
1136
|
those slots, so ``DG01`` is wire index 0. On a default account the four
|
|
@@ -1121,43 +1148,92 @@ class CronometerClient:
|
|
|
1121
1148
|
List of dicts ordered by wire index, each with ``wire_index``
|
|
1122
1149
|
(int), ``settings_key`` (str), ``name`` (str) and ``enabled``
|
|
1123
1150
|
(bool). Empty list if the response carries no DG keys.
|
|
1151
|
+
|
|
1152
|
+
Raises:
|
|
1153
|
+
DiaryGroupsUnreadable: DG keys are present but cannot be read.
|
|
1124
1154
|
"""
|
|
1155
|
+
dg_keys = [
|
|
1156
|
+
f"DG{slot:02d}{suffix}"
|
|
1157
|
+
for slot in range(1, DIARY_GROUP_SLOTS + 1)
|
|
1158
|
+
for suffix in ("", "ON")
|
|
1159
|
+
]
|
|
1125
1160
|
try:
|
|
1126
1161
|
table = CronometerClient._extract_gwt_string_table(raw)
|
|
1127
1162
|
except Exception:
|
|
1163
|
+
if '"DG0' in raw:
|
|
1164
|
+
raise DiaryGroupsUnreadable("string table unreadable")
|
|
1128
1165
|
return []
|
|
1129
1166
|
if not table:
|
|
1130
1167
|
return []
|
|
1131
1168
|
|
|
1132
1169
|
ref_of = {s: str(i + 1) for i, s in enumerate(table)}
|
|
1170
|
+
if not any(k in ref_of for k in dg_keys):
|
|
1171
|
+
return []
|
|
1133
1172
|
body = raw[: raw.rindex('["')]
|
|
1134
1173
|
tokens = [tok for tok in body.split(",") if tok.strip()]
|
|
1135
1174
|
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
return
|
|
1175
|
+
string_type = next(
|
|
1176
|
+
(ref_of[s] for s in table if s.startswith("java.lang.String/")), None
|
|
1177
|
+
)
|
|
1178
|
+
if string_type is None:
|
|
1179
|
+
raise DiaryGroupsUnreadable("no java.lang.String type in the response")
|
|
1180
|
+
|
|
1181
|
+
positions: dict[str, list[int]] = {}
|
|
1182
|
+
for pos, tok in enumerate(tokens):
|
|
1183
|
+
positions.setdefault(tok, []).append(pos)
|
|
1184
|
+
|
|
1185
|
+
def occurrences(key: str) -> list[int]:
|
|
1186
|
+
return positions.get(ref_of.get(key, ""), [])
|
|
1187
|
+
|
|
1188
|
+
def is_entry_key(pos: int) -> bool:
|
|
1189
|
+
# A [String, value, String, key] settings entry.
|
|
1190
|
+
return (
|
|
1191
|
+
pos >= 3
|
|
1192
|
+
and tokens[pos - 1] == string_type
|
|
1193
|
+
and tokens[pos - 3] == string_type
|
|
1194
|
+
and tokens[pos - 2].isdigit()
|
|
1195
|
+
)
|
|
1196
|
+
|
|
1197
|
+
# Settings entries are four tokens wide, so every real key sits at the
|
|
1198
|
+
# same position mod 4. A value that happens to equal a DG key (a group
|
|
1199
|
+
# renamed "DG06") also looks like an entry key, but two tokens off that
|
|
1200
|
+
# phase. Take the phase most DG keys agree on; a tie is unreadable.
|
|
1201
|
+
phases = Counter(
|
|
1202
|
+
pos % 4 for k in dg_keys for pos in occurrences(k) if is_entry_key(pos)
|
|
1203
|
+
).most_common(2)
|
|
1204
|
+
if not phases or (len(phases) == 2 and phases[0][1] == phases[1][1]):
|
|
1205
|
+
raise DiaryGroupsUnreadable("settings entry phase undecidable")
|
|
1206
|
+
phase = phases[0][0]
|
|
1207
|
+
|
|
1208
|
+
def lookup(key: str) -> tuple[set[str | None], bool]:
|
|
1209
|
+
"""The key's settings values, and whether any occurrence is unexplained."""
|
|
1210
|
+
values: set[str | None] = set()
|
|
1211
|
+
unexplained = False
|
|
1212
|
+
for pos in occurrences(key):
|
|
1213
|
+
if pos % 4 == phase and is_entry_key(pos):
|
|
1214
|
+
i = int(tokens[pos - 2])
|
|
1215
|
+
values.add(table[i - 1] if 0 < i <= len(table) else None)
|
|
1216
|
+
elif not (pos % 4 == (phase + 2) % 4 and tokens[pos - 1] == string_type):
|
|
1217
|
+
unexplained = True # not another entry's value either
|
|
1218
|
+
return values, unexplained
|
|
1148
1219
|
|
|
1149
1220
|
groups = []
|
|
1150
1221
|
for slot in range(1, DIARY_GROUP_SLOTS + 1):
|
|
1151
1222
|
key = f"DG{slot:02d}"
|
|
1152
|
-
|
|
1153
|
-
if
|
|
1223
|
+
names, _ = lookup(key)
|
|
1224
|
+
if len(names) != 1 or None in names:
|
|
1154
1225
|
continue
|
|
1226
|
+
flags, unexplained = lookup(f"{key}ON")
|
|
1155
1227
|
groups.append({
|
|
1156
1228
|
"wire_index": slot - 1,
|
|
1157
1229
|
"settings_key": key,
|
|
1158
|
-
"name":
|
|
1159
|
-
|
|
1230
|
+
"name": names.pop(),
|
|
1231
|
+
# Only a flag missing from the response means enabled; one that
|
|
1232
|
+
# is unreadable or conflicting stays disabled (fail closed).
|
|
1233
|
+
"enabled": flags == {"true"} or (not flags and not unexplained),
|
|
1160
1234
|
})
|
|
1235
|
+
if not groups:
|
|
1236
|
+
raise DiaryGroupsUnreadable("DG settings present but no group parsed")
|
|
1161
1237
|
return groups
|
|
1162
1238
|
|
|
1163
1239
|
def _fetch_diary_groups(self) -> list[dict]:
|
|
@@ -1186,9 +1262,10 @@ class CronometerClient:
|
|
|
1186
1262
|
restored session fetches lazily on first access, so callers that never
|
|
1187
1263
|
touch diary groups never pay for it.
|
|
1188
1264
|
|
|
1189
|
-
Falls back to the four default meals at wire 1-4
|
|
1190
|
-
|
|
1191
|
-
|
|
1265
|
+
Falls back to the four default meals at wire 1-4 only when the
|
|
1266
|
+
response carries no DG settings at all. DG settings that are present
|
|
1267
|
+
but unreadable raise DiaryGroupsUnreadable instead (not cached, so the
|
|
1268
|
+
next access retries): the defaults could enable a disabled group. A failed fetch (timeout, dead session) is
|
|
1192
1269
|
not a parse regression: it raises and is retried on the next access,
|
|
1193
1270
|
since the defaults would send writes to the wrong group on an account
|
|
1194
1271
|
with custom groups.
|
|
@@ -1209,6 +1286,8 @@ class CronometerClient:
|
|
|
1209
1286
|
def get_food(self, food_source_id: int) -> dict:
|
|
1210
1287
|
"""Get detailed food information including available measures.
|
|
1211
1288
|
|
|
1289
|
+
Backed by FOOD_URL, not GWT-RPC: Cronometer removed the getFood RPC.
|
|
1290
|
+
|
|
1212
1291
|
Args:
|
|
1213
1292
|
food_source_id: Food source ID from find_foods results.
|
|
1214
1293
|
|
|
@@ -1216,149 +1295,37 @@ class CronometerClient:
|
|
|
1216
1295
|
Dict with keys:
|
|
1217
1296
|
|
|
1218
1297
|
- ``food_source_id`` (int): Echo of the input.
|
|
1219
|
-
- ``raw_response`` (str): Raw GWT-RPC response for debugging.
|
|
1220
1298
|
- ``measures`` (list[dict]): Available serving measures, each with:
|
|
1221
|
-
- ``measure_id`` (int):
|
|
1222
|
-
|
|
1223
|
-
|
|
1299
|
+
- ``measure_id`` (int): Cronometer's REST measure id. Not for
|
|
1300
|
+
add_serving: these ids exceed the 16 bits add_serving keeps,
|
|
1301
|
+
so pass measure_id=0 there with this measure's weight_grams.
|
|
1302
|
+
- ``description`` (str): Measure name (e.g. ``"large"``).
|
|
1224
1303
|
- ``weight_grams`` (float): Weight in grams for this measure.
|
|
1225
|
-
"""
|
|
1226
|
-
self.authenticate()
|
|
1227
|
-
body = (
|
|
1228
|
-
GWT_GET_FOOD
|
|
1229
|
-
.replace("{gwt_header}", self.gwt_header)
|
|
1230
|
-
.replace("{nonce}", self.nonce or "")
|
|
1231
|
-
.replace("{food_source_id}", str(food_source_id))
|
|
1232
|
-
)
|
|
1233
|
-
raw = self._gwt_post(body)
|
|
1234
|
-
return self._parse_get_food(raw, food_source_id)
|
|
1235
1304
|
|
|
1236
|
-
|
|
1237
|
-
def _parse_get_food(raw: str, food_source_id: int) -> dict:
|
|
1238
|
-
"""Parse a getFood GWT-RPC response to extract measure information.
|
|
1239
|
-
|
|
1240
|
-
The response contains food metadata and a list of Measure objects.
|
|
1241
|
-
Each Measure has fields (reading backwards from the Measure type ref):
|
|
1242
|
-
|
|
1243
|
-
i-6 description_ref (1-based string table index)
|
|
1244
|
-
i-5 flags (0)
|
|
1245
|
-
i-4 measure_id (integer, the key value needed by add_serving)
|
|
1246
|
-
i-3 food_source_id
|
|
1247
|
-
i-2 flags (0)
|
|
1248
|
-
i-1 quantity (1.0)
|
|
1249
|
-
i <Measure type ref>
|
|
1250
|
-
|
|
1251
|
-
Weight in grams is a float that appears earlier in the token stream,
|
|
1252
|
-
before the Measure$Type ref/back-ref for each measure.
|
|
1305
|
+
Derived measures are left out, as the GWT parser did before.
|
|
1253
1306
|
"""
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
closing = ",0,7]"
|
|
1264
|
-
st_close = len(raw) - len(closing) - 1
|
|
1265
|
-
depth, pos, in_str = 1, st_close - 1, False
|
|
1266
|
-
while pos >= 0 and depth > 0:
|
|
1267
|
-
ch = raw[pos]
|
|
1268
|
-
if ch == '"' and (pos == 0 or raw[pos - 1] != "\\"):
|
|
1269
|
-
in_str = not in_str
|
|
1270
|
-
elif not in_str:
|
|
1271
|
-
if ch == "]":
|
|
1272
|
-
depth += 1
|
|
1273
|
-
elif ch == "[":
|
|
1274
|
-
depth -= 1
|
|
1275
|
-
pos -= 1
|
|
1276
|
-
st_open = pos + 1
|
|
1277
|
-
string_table: list[str] = json.loads(raw[st_open : st_close + 1])
|
|
1278
|
-
|
|
1279
|
-
def _resolve(ref: int) -> str | None:
|
|
1280
|
-
if 1 <= ref <= len(string_table):
|
|
1281
|
-
return string_table[ref - 1]
|
|
1282
|
-
return None
|
|
1283
|
-
|
|
1284
|
-
# Find Measure class index in string table
|
|
1285
|
-
measure_type_idx: int | None = None
|
|
1286
|
-
for idx, entry in enumerate(string_table):
|
|
1287
|
-
if entry.startswith("["):
|
|
1307
|
+
food = self._rest_get_json(FOOD_URL.format(food_source_id=food_source_id))
|
|
1308
|
+
measures = food.get("measures") if isinstance(food, dict) else None
|
|
1309
|
+
if not isinstance(measures, list):
|
|
1310
|
+
raise ValueError(f"Food {food_source_id}: no measures list in response")
|
|
1311
|
+
result = []
|
|
1312
|
+
for m in measures:
|
|
1313
|
+
if not isinstance(m, dict):
|
|
1314
|
+
raise ValueError(f"Food {food_source_id}: malformed measure {m!r}")
|
|
1315
|
+
if m.get("derived"):
|
|
1288
1316
|
continue
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
return result
|
|
1300
|
-
|
|
1301
|
-
tokens: list = []
|
|
1302
|
-
for part in data_section.split(","):
|
|
1303
|
-
part = part.strip()
|
|
1304
|
-
if not part:
|
|
1305
|
-
continue
|
|
1306
|
-
# Handle quoted strings (e.g. serving_id in Food metadata)
|
|
1307
|
-
if part.startswith('"') and part.endswith('"'):
|
|
1308
|
-
tokens.append(part)
|
|
1309
|
-
continue
|
|
1310
|
-
try:
|
|
1311
|
-
tokens.append(float(part) if "." in part else int(part))
|
|
1312
|
-
except ValueError:
|
|
1313
|
-
tokens.append(None)
|
|
1314
|
-
|
|
1315
|
-
# Scan for Measure type-index occurrences and extract fields.
|
|
1316
|
-
measures = []
|
|
1317
|
-
for i, token in enumerate(tokens):
|
|
1318
|
-
if token != measure_type_idx:
|
|
1319
|
-
continue
|
|
1320
|
-
if i < 6:
|
|
1321
|
-
continue
|
|
1322
|
-
|
|
1323
|
-
measure_id_val = tokens[i - 4]
|
|
1324
|
-
|
|
1325
|
-
if not isinstance(measure_id_val, int):
|
|
1326
|
-
continue
|
|
1327
|
-
|
|
1328
|
-
# Description ref is at i-6 for standard Measure layout, but
|
|
1329
|
-
# CRDB foods with a boxed Double field shift it to i-7 or i-8.
|
|
1330
|
-
# Scan multiple offsets to find a valid description string.
|
|
1331
|
-
description = ""
|
|
1332
|
-
for offset in (6, 7, 8):
|
|
1333
|
-
if i < offset:
|
|
1334
|
-
continue
|
|
1335
|
-
ref = tokens[i - offset]
|
|
1336
|
-
if isinstance(ref, int) and 1 <= ref <= len(string_table):
|
|
1337
|
-
candidate = string_table[ref - 1]
|
|
1338
|
-
if (candidate
|
|
1339
|
-
and not candidate.startswith("com.")
|
|
1340
|
-
and not candidate.startswith("java.")
|
|
1341
|
-
and not candidate.startswith("[")):
|
|
1342
|
-
description = candidate
|
|
1343
|
-
break
|
|
1344
|
-
|
|
1345
|
-
# Find weight_grams: it's the float that appears before the
|
|
1346
|
-
# Measure$Type ref/back-ref, which is at i-7 or i-8.
|
|
1347
|
-
# Scan backwards from i-7 to find the first float.
|
|
1348
|
-
weight_grams = 0.0
|
|
1349
|
-
for j in range(i - 7, max(i - 12, -1), -1):
|
|
1350
|
-
if isinstance(tokens[j], float):
|
|
1351
|
-
weight_grams = tokens[j]
|
|
1352
|
-
break
|
|
1353
|
-
|
|
1354
|
-
measures.append({
|
|
1355
|
-
"measure_id": measure_id_val,
|
|
1356
|
-
"description": description or "",
|
|
1357
|
-
"weight_grams": round(weight_grams, 2),
|
|
1317
|
+
mid, grams = m.get("id"), m.get("value")
|
|
1318
|
+
if (not isinstance(mid, int) or not isinstance(grams, (int, float))
|
|
1319
|
+
or isinstance(mid, bool) or isinstance(grams, bool)):
|
|
1320
|
+
raise ValueError(
|
|
1321
|
+
f"Food {food_source_id}: malformed measure (id={mid!r}, value={grams!r})"
|
|
1322
|
+
)
|
|
1323
|
+
result.append({
|
|
1324
|
+
"measure_id": mid,
|
|
1325
|
+
"description": m.get("name") or "",
|
|
1326
|
+
"weight_grams": round(grams, 2),
|
|
1358
1327
|
})
|
|
1359
|
-
|
|
1360
|
-
result["measures"] = measures
|
|
1361
|
-
return result
|
|
1328
|
+
return {"food_source_id": food_source_id, "measures": result}
|
|
1362
1329
|
|
|
1363
1330
|
def add_serving(
|
|
1364
1331
|
self,
|
|
@@ -469,7 +469,7 @@ def search_foods(query: str) -> str:
|
|
|
469
469
|
"""Search Cronometer's food database by name.
|
|
470
470
|
|
|
471
471
|
Returns matching foods with their IDs and source information needed
|
|
472
|
-
to add a serving (food_id, food_source_id
|
|
472
|
+
to add a serving (food_id, food_source_id).
|
|
473
473
|
|
|
474
474
|
Args:
|
|
475
475
|
query: Food name or keyword to search for (e.g. "eggs", "chicken breast").
|
|
@@ -494,8 +494,10 @@ def search_foods(query: str) -> str:
|
|
|
494
494
|
def get_food_details(food_source_id: int) -> str:
|
|
495
495
|
"""Get detailed food information including available serving measures.
|
|
496
496
|
|
|
497
|
-
Use this after search_foods to
|
|
498
|
-
|
|
497
|
+
Use this after search_foods to find a serving's gram weight (e.g. one
|
|
498
|
+
large egg = 50 g), then call add_food_entry with that weight_grams and
|
|
499
|
+
measure_id left at 0. The measure_id values listed here are for reference
|
|
500
|
+
only: don't pass them to add_food_entry.
|
|
499
501
|
|
|
500
502
|
Args:
|
|
501
503
|
food_source_id: Food source ID from search_foods results.
|
|
@@ -503,7 +505,6 @@ def get_food_details(food_source_id: int) -> str:
|
|
|
503
505
|
try:
|
|
504
506
|
client = _get_client()
|
|
505
507
|
result = client.get_food(food_source_id)
|
|
506
|
-
# Remove raw_response from the output to keep it clean
|
|
507
508
|
output = {
|
|
508
509
|
"status": "success",
|
|
509
510
|
"food_source_id": result["food_source_id"],
|
|
@@ -526,12 +527,12 @@ def add_food_entry(
|
|
|
526
527
|
) -> str:
|
|
527
528
|
"""Add a food entry to the Cronometer diary.
|
|
528
529
|
|
|
529
|
-
Use search_foods to find food_id and food_source_id,
|
|
530
|
-
get_food_details for
|
|
530
|
+
Use search_foods to find food_id and food_source_id, and
|
|
531
|
+
get_food_details for a serving's weight_grams.
|
|
531
532
|
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
533
|
+
Leave measure_id at 0 (the default): it uses a universal gram-based
|
|
534
|
+
measure that works for all food sources, and quantity is set to
|
|
535
|
+
weight_grams. Don't pass measure_id values from get_food_details.
|
|
535
536
|
|
|
536
537
|
Args:
|
|
537
538
|
food_id: Numeric food ID from search_foods results.
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "cronometer-mcp"
|
|
7
|
-
version = "2.4.
|
|
7
|
+
version = "2.4.4"
|
|
8
8
|
description = "MCP server for Cronometer nutrition data — pull food logs, macros, and micronutrients via the Model Context Protocol"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "MIT"
|
|
@@ -6,12 +6,12 @@
|
|
|
6
6
|
"url": "https://github.com/cphoskins/cronometer-mcp",
|
|
7
7
|
"source": "github"
|
|
8
8
|
},
|
|
9
|
-
"version": "2.4.
|
|
9
|
+
"version": "2.4.4",
|
|
10
10
|
"packages": [
|
|
11
11
|
{
|
|
12
12
|
"registryType": "pypi",
|
|
13
13
|
"identifier": "cronometer-mcp",
|
|
14
|
-
"version": "2.4.
|
|
14
|
+
"version": "2.4.4",
|
|
15
15
|
"transport": {
|
|
16
16
|
"type": "stdio"
|
|
17
17
|
},
|
|
@@ -745,145 +745,155 @@ class TestFindFoodsIntegration:
|
|
|
745
745
|
assert food["food_id"] == 66395420
|
|
746
746
|
|
|
747
747
|
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
# ---------------------------------------------------------------------------
|
|
751
|
-
|
|
752
|
-
def _build_get_food_response(measures: list[dict], include_derived: bool = False) -> str:
|
|
753
|
-
"""Build a minimal //OK[...] getFood response with Measure objects.
|
|
748
|
+
class TestGetFood:
|
|
749
|
+
"""Tests for get_food() — now backed by the REST food API.
|
|
754
750
|
|
|
755
|
-
|
|
751
|
+
Cronometer removed the getFood GWT-RPC method (2026-12-05: it no longer
|
|
752
|
+
appears in the CronometerService method table, and calling it returns
|
|
753
|
+
IncompatibleRemoteServiceException). The web app now fetches
|
|
754
|
+
GET /api/v3/food/{food_source_id}.
|
|
756
755
|
"""
|
|
757
|
-
import json as _json
|
|
758
756
|
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
"
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
"
|
|
757
|
+
@staticmethod
|
|
758
|
+
def _measure(measure_id, name, grams, derived=False):
|
|
759
|
+
"""One REST measure, trimmed from a live response (eggs, 464674)."""
|
|
760
|
+
return {
|
|
761
|
+
"id": measure_id,
|
|
762
|
+
"name": name,
|
|
763
|
+
"value": grams,
|
|
764
|
+
"amount": 1.0,
|
|
765
|
+
"type": "Weight",
|
|
766
|
+
"derived": derived,
|
|
767
|
+
"derivable": False,
|
|
768
|
+
"hidden": False,
|
|
769
|
+
"translations": [],
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
def _mock_get(self, client, payload, status=200):
|
|
773
|
+
resp = MagicMock(status_code=status, json=lambda: payload)
|
|
774
|
+
resp.raise_for_status = MagicMock()
|
|
775
|
+
get_mock = MagicMock(return_value=resp)
|
|
776
|
+
client._authenticated = True
|
|
777
|
+
client.user_id = "42"
|
|
778
|
+
client.session.get = get_mock
|
|
779
|
+
client.session.post = MagicMock(
|
|
780
|
+
side_effect=AssertionError("get_food must not use GWT-RPC")
|
|
767
781
|
)
|
|
782
|
+
return get_mock
|
|
768
783
|
|
|
769
|
-
|
|
784
|
+
def test_hits_rest_food_url(self, client):
|
|
785
|
+
get_mock = self._mock_get(client, {"id": 464674, "measures": []})
|
|
770
786
|
|
|
771
|
-
|
|
772
|
-
combined = class_names + data_strings
|
|
773
|
-
if s in combined:
|
|
774
|
-
return combined.index(s) + 1
|
|
775
|
-
data_strings.append(s)
|
|
776
|
-
return len(class_names) + len(data_strings)
|
|
787
|
+
client.get_food(464674)
|
|
777
788
|
|
|
778
|
-
|
|
779
|
-
measure_subtype_idx = 3 # Measure$Type
|
|
789
|
+
assert get_mock.call_args[0][0] == "https://cronometer.com/api/v3/food/464674"
|
|
780
790
|
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
791
|
+
def test_maps_measures(self, client):
|
|
792
|
+
self._mock_get(client, {"id": 464674, "measures": [
|
|
793
|
+
self._measure(1072101, "large", 50.0),
|
|
794
|
+
self._measure(1072106, "tsp, chopped", 2.8333570200000002),
|
|
795
|
+
]})
|
|
784
796
|
|
|
785
|
-
|
|
786
|
-
desc_ref = _intern(m["description"])
|
|
787
|
-
# Layout: weight_grams, ..., Measure$Type ref, ...,
|
|
788
|
-
# desc_ref, 0, measure_id, food_source_id, 0, 1.0, Measure type ref
|
|
789
|
-
data_tokens += [
|
|
790
|
-
m["weight_grams"], # weight_grams (float)
|
|
791
|
-
0, # padding
|
|
792
|
-
measure_subtype_idx, # Measure$Type ref
|
|
793
|
-
0, # ordinal
|
|
794
|
-
desc_ref, # description (i-6 from Measure type ref)
|
|
795
|
-
0, # flags (i-5)
|
|
796
|
-
m["measure_id"], # measure_id (i-4)
|
|
797
|
-
m["food_source_id"], # food_source_id (i-3)
|
|
798
|
-
0, # flags (i-2)
|
|
799
|
-
1.0, # quantity (i-1)
|
|
800
|
-
measure_type_idx, # Measure type ref (i)
|
|
801
|
-
]
|
|
797
|
+
result = client.get_food(464674)
|
|
802
798
|
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
_intern("mL"), 0, 999999, 12345, 0, 1.0,
|
|
808
|
-
derived_type_idx,
|
|
799
|
+
assert result["food_source_id"] == 464674
|
|
800
|
+
assert result["measures"] == [
|
|
801
|
+
{"measure_id": 1072101, "description": "large", "weight_grams": 50.0},
|
|
802
|
+
{"measure_id": 1072106, "description": "tsp, chopped", "weight_grams": 2.83},
|
|
809
803
|
]
|
|
810
804
|
|
|
811
|
-
|
|
812
|
-
|
|
805
|
+
def test_derived_measure_excluded(self, client):
|
|
806
|
+
self._mock_get(client, {"id": 500, "measures": [
|
|
807
|
+
self._measure(200, "tbsp", 14.0),
|
|
808
|
+
self._measure(999999, "mL", 1.0, derived=True),
|
|
809
|
+
]})
|
|
813
810
|
|
|
814
|
-
|
|
815
|
-
token_strs = []
|
|
816
|
-
for t in data_tokens:
|
|
817
|
-
if isinstance(t, float):
|
|
818
|
-
token_strs.append(str(t))
|
|
819
|
-
else:
|
|
820
|
-
token_strs.append(str(t))
|
|
821
|
-
tokens_str = ",".join(token_strs)
|
|
811
|
+
ids = [m["measure_id"] for m in client.get_food(500)["measures"]]
|
|
822
812
|
|
|
823
|
-
|
|
813
|
+
assert ids == [200]
|
|
824
814
|
|
|
815
|
+
def test_reauthenticates_once_on_401(self, client):
|
|
816
|
+
ok = MagicMock(status_code=200, json=lambda: {"id": 1, "measures": []})
|
|
817
|
+
denied = MagicMock(status_code=401)
|
|
818
|
+
client._authenticated = True
|
|
819
|
+
client.session.get = MagicMock(side_effect=[denied, ok])
|
|
820
|
+
with patch.object(client, "_reauthenticate") as reauth:
|
|
821
|
+
assert client.get_food(1)["measures"] == []
|
|
822
|
+
reauth.assert_called_once()
|
|
825
823
|
|
|
826
|
-
|
|
827
|
-
|
|
824
|
+
def test_http_error_raises(self, client):
|
|
825
|
+
get_mock = self._mock_get(client, {}, status=404)
|
|
826
|
+
get_mock.return_value.raise_for_status.side_effect = requests.HTTPError("404")
|
|
828
827
|
|
|
829
|
-
|
|
830
|
-
|
|
828
|
+
with pytest.raises(requests.HTTPError):
|
|
829
|
+
client.get_food(1)
|
|
831
830
|
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
""
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
831
|
+
@staticmethod
|
|
832
|
+
def _html_page():
|
|
833
|
+
"""A 200 that is not JSON, e.g. a login page after a redirect."""
|
|
834
|
+
def not_json():
|
|
835
|
+
raise requests.JSONDecodeError("Expecting value", "<html>", 0)
|
|
836
|
+
return MagicMock(status_code=200, json=not_json, url="https://cronometer.com/login/")
|
|
837
|
+
|
|
838
|
+
def test_reauthenticates_once_on_non_json_page(self, client):
|
|
839
|
+
ok = MagicMock(status_code=200, json=lambda: {"id": 1, "measures": []})
|
|
840
|
+
client._authenticated = True
|
|
841
|
+
client.session.get = MagicMock(side_effect=[self._html_page(), ok])
|
|
842
|
+
with patch.object(client, "_reauthenticate") as reauth:
|
|
843
|
+
assert client.get_food(1)["measures"] == []
|
|
844
|
+
reauth.assert_called_once()
|
|
845
|
+
|
|
846
|
+
def test_non_json_after_relogin_raises_clear_error(self, client):
|
|
847
|
+
client._authenticated = True
|
|
848
|
+
client.session.get = MagicMock(side_effect=[self._html_page(), self._html_page()])
|
|
849
|
+
with patch.object(client, "_reauthenticate"):
|
|
850
|
+
with pytest.raises(RuntimeError, match="not JSON"):
|
|
851
|
+
client.get_food(1)
|
|
852
|
+
|
|
853
|
+
@pytest.mark.parametrize("payload", [
|
|
854
|
+
{"id": 1, "measures": None},
|
|
855
|
+
{"id": 1, "measures": [{"id": 5, "name": "large", "value": None}]},
|
|
856
|
+
{"id": 1, "measures": [{"name": "large", "value": 50.0}]},
|
|
857
|
+
{"id": 1, "measures": [{"id": 5, "name": "large"}]},
|
|
858
|
+
{"id": 1},
|
|
859
|
+
{"id": 1, "measures": [None]},
|
|
860
|
+
{"id": 1, "measures": ["large"]},
|
|
861
|
+
{"id": 1, "measures": [{"id": True, "name": "large", "value": 50.0}]},
|
|
862
|
+
{"id": 1, "measures": [{"id": 5, "name": "large", "value": False}]},
|
|
863
|
+
])
|
|
864
|
+
def test_malformed_measures_raise_clear_error(self, client, payload):
|
|
865
|
+
self._mock_get(client, payload)
|
|
866
|
+
with pytest.raises(ValueError, match="measure"):
|
|
867
|
+
client.get_food(1)
|
|
868
|
+
|
|
869
|
+
def test_null_name_becomes_empty_string(self, client):
|
|
870
|
+
self._mock_get(client, {"id": 1, "measures": [
|
|
871
|
+
{"id": 5, "name": None, "value": 50.0}]})
|
|
872
|
+
assert client.get_food(1)["measures"][0]["description"] == ""
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
class TestFindFoodsReauth:
|
|
876
|
+
def test_reauthenticates_once_on_non_json_page(self, client):
|
|
877
|
+
ok = MagicMock(status_code=200, json=lambda: [])
|
|
878
|
+
client._authenticated = True
|
|
879
|
+
client.user_id = "42"
|
|
880
|
+
client.session.get = MagicMock(side_effect=[TestGetFood._html_page(), ok])
|
|
881
|
+
with patch.object(client, "_reauthenticate") as reauth:
|
|
882
|
+
assert client.find_foods("egg") == []
|
|
883
|
+
reauth.assert_called_once()
|
|
884
|
+
|
|
885
|
+
def test_logs_in_before_building_url(self, client):
|
|
886
|
+
"""user_id is only known after login; the URL must not say user/None."""
|
|
887
|
+
client._authenticated = False
|
|
888
|
+
client.user_id = None
|
|
889
|
+
client.session.get = MagicMock(return_value=MagicMock(status_code=200, json=lambda: []))
|
|
890
|
+
|
|
891
|
+
def login():
|
|
892
|
+
client._authenticated = True
|
|
893
|
+
client.user_id = "42"
|
|
894
|
+
with patch.object(client, "authenticate", side_effect=login):
|
|
895
|
+
client.find_foods("egg")
|
|
896
|
+
assert "/user/42/" in client.session.get.call_args[0][0]
|
|
887
897
|
|
|
888
898
|
|
|
889
899
|
class TestAddServing:
|
|
@@ -11,7 +11,7 @@ from unittest.mock import MagicMock
|
|
|
11
11
|
import pytest
|
|
12
12
|
import requests
|
|
13
13
|
|
|
14
|
-
from cronometer_mcp.client import CronometerClient
|
|
14
|
+
from cronometer_mcp.client import CronometerClient, DiaryGroupsUnreadable
|
|
15
15
|
from cronometer_mcp.server import _resolve_diary_group
|
|
16
16
|
|
|
17
17
|
|
|
@@ -26,10 +26,11 @@ def build_settings_response(settings: dict[str, str]) -> str:
|
|
|
26
26
|
de-duplicated, which is what breaks naive adjacency for shared values like
|
|
27
27
|
"true"/"false".
|
|
28
28
|
"""
|
|
29
|
-
table: list[str] = [
|
|
30
|
-
# pad so the type
|
|
31
|
-
while len(table) < int(STRING_TYPE_REF):
|
|
29
|
+
table: list[str] = []
|
|
30
|
+
# pad so the String type lands on ref 54, matching the real payload's layout
|
|
31
|
+
while len(table) < int(STRING_TYPE_REF) - 1:
|
|
32
32
|
table.append(f"filler.{len(table)}")
|
|
33
|
+
table.append("java.lang.String/2004016611")
|
|
33
34
|
|
|
34
35
|
def ref(s: str) -> str:
|
|
35
36
|
if s not in table:
|
|
@@ -114,6 +115,75 @@ class TestParseDiaryGroups:
|
|
|
114
115
|
assert by_name["dinner"] == 3
|
|
115
116
|
assert by_name["snacks"] == 4
|
|
116
117
|
|
|
118
|
+
def test_unreadable_enable_flag_stays_disabled(self):
|
|
119
|
+
"""A flag that is present but unreadable must not count as omitted.
|
|
120
|
+
|
|
121
|
+
Another field's double followed by an int equal to the flag key's
|
|
122
|
+
ref makes the parser find the key at the wrong position.
|
|
123
|
+
"""
|
|
124
|
+
raw = build_settings_response(DEFAULT_ACCOUNT)
|
|
125
|
+
table = CronometerClient._extract_gwt_string_table(raw)
|
|
126
|
+
ref = table.index("DG06ON") + 1
|
|
127
|
+
raw = raw.replace("//OK[0,0,1,", f"//OK[0,0,1,70.5,9,{ref},", 1)
|
|
128
|
+
|
|
129
|
+
groups = CronometerClient._parse_diary_groups(raw)
|
|
130
|
+
assert {g["settings_key"]: g["enabled"] for g in groups}["DG06"] is False
|
|
131
|
+
|
|
132
|
+
@pytest.mark.parametrize("key", ["DG02ON", "DG06ON"])
|
|
133
|
+
def test_readable_collision_does_not_enable_group(self, key):
|
|
134
|
+
"""A stray "true" ref before the flag key's ref is not its value.
|
|
135
|
+
|
|
136
|
+
Only a [String, value, String, key] settings entry counts.
|
|
137
|
+
"""
|
|
138
|
+
raw = build_settings_response(dict(DEFAULT_ACCOUNT, **{key: "false"}))
|
|
139
|
+
table = CronometerClient._extract_gwt_string_table(raw)
|
|
140
|
+
true_ref = table.index("true") + 1
|
|
141
|
+
flag_ref = table.index(key) + 1
|
|
142
|
+
raw = raw.replace("//OK[0,0,1,", f"//OK[0,0,1,{true_ref},9,{flag_ref},", 1)
|
|
143
|
+
|
|
144
|
+
groups = CronometerClient._parse_diary_groups(raw)
|
|
145
|
+
assert {g["settings_key"]: g["enabled"] for g in groups}[key[:4]] is False
|
|
146
|
+
|
|
147
|
+
def test_conflicting_settings_entries_count_as_unreadable(self):
|
|
148
|
+
"""Two well-formed entries for one flag with different values: fail closed."""
|
|
149
|
+
raw = build_settings_response(DEFAULT_ACCOUNT)
|
|
150
|
+
table = CronometerClient._extract_gwt_string_table(raw)
|
|
151
|
+
ref = {s: str(i + 1) for i, s in enumerate(table)}
|
|
152
|
+
raw = raw.replace(
|
|
153
|
+
"//OK[0,0,1,",
|
|
154
|
+
f"//OK[0,0,1,{STRING_TYPE_REF},{ref['true']},{STRING_TYPE_REF},{ref['DG06ON']},",
|
|
155
|
+
1,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
groups = CronometerClient._parse_diary_groups(raw)
|
|
159
|
+
assert {g["settings_key"]: g["enabled"] for g in groups}["DG06"] is False
|
|
160
|
+
|
|
161
|
+
@staticmethod
|
|
162
|
+
def _by_key(settings):
|
|
163
|
+
return {
|
|
164
|
+
g["settings_key"]: g
|
|
165
|
+
for g in CronometerClient._parse_diary_groups(
|
|
166
|
+
build_settings_response(settings)
|
|
167
|
+
)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
def test_value_equal_to_a_name_key_is_not_that_key(self):
|
|
171
|
+
"""Overlapping windows: DG08's value "DG06" must not shadow the DG06 entry."""
|
|
172
|
+
groups = self._by_key(dict(DEFAULT_ACCOUNT, DG08="DG06"))
|
|
173
|
+
assert groups["DG08"]["name"] == "DG06"
|
|
174
|
+
assert groups["DG06"]["name"] == "Group 6"
|
|
175
|
+
|
|
176
|
+
def test_value_equal_to_an_omitted_flag_key_does_not_disable(self):
|
|
177
|
+
settings = dict(DEFAULT_ACCOUNT, DG08="DG04ON")
|
|
178
|
+
settings.pop("DG04ON")
|
|
179
|
+
assert self._by_key(settings)["DG04"]["enabled"] is True
|
|
180
|
+
|
|
181
|
+
def test_value_equal_to_an_absent_name_key_invents_no_group(self):
|
|
182
|
+
settings = dict(DEFAULT_ACCOUNT, DG08="DG06")
|
|
183
|
+
settings.pop("DG06")
|
|
184
|
+
settings.pop("DG06ON")
|
|
185
|
+
assert "DG06" not in self._by_key(settings)
|
|
186
|
+
|
|
117
187
|
def test_returns_empty_when_no_dg_keys(self):
|
|
118
188
|
assert CronometerClient._parse_diary_groups(
|
|
119
189
|
build_settings_response({"weightInKG": "80.0"})
|
|
@@ -151,6 +221,73 @@ class TestDiaryGroupsFallback:
|
|
|
151
221
|
assert c._diary_groups is None # not cached; the next call retries
|
|
152
222
|
|
|
153
223
|
|
|
224
|
+
def _without_string_type(raw: str) -> str:
|
|
225
|
+
return raw.replace('"java.lang.String/2004016611"', '"x.NotAString/1"')
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
# Every slot renamed to another slot's key with no flags: the DG names tie the
|
|
229
|
+
# phase vote 8-8 with the DG keys, so which tokens are keys is undecidable.
|
|
230
|
+
TIED_PHASE_ACCOUNT = {"weightInKG": "80.0"} | {
|
|
231
|
+
f"DG{slot:02d}": f"DG{slot % 8 + 1:02d}" for slot in range(1, 9)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class TestUnreadableDiaryGroups:
|
|
236
|
+
"""DG settings that are present but unreadable must never become the
|
|
237
|
+
enabled default meals: that can enable a disabled slot or rename one."""
|
|
238
|
+
|
|
239
|
+
@pytest.mark.parametrize("raw", [
|
|
240
|
+
_without_string_type(build_settings_response(DEFAULT_ACCOUNT)),
|
|
241
|
+
build_settings_response(TIED_PHASE_ACCOUNT),
|
|
242
|
+
], ids=["no-string-type", "tied-phase"])
|
|
243
|
+
def test_parse_raises(self, raw):
|
|
244
|
+
with pytest.raises(DiaryGroupsUnreadable):
|
|
245
|
+
CronometerClient._parse_diary_groups(raw)
|
|
246
|
+
|
|
247
|
+
def test_property_raises_and_retries_next_access(self, monkeypatch):
|
|
248
|
+
c = CronometerClient(username="u", password="p")
|
|
249
|
+
monkeypatch.setattr(c, "authenticate", lambda: None)
|
|
250
|
+
|
|
251
|
+
def unreadable():
|
|
252
|
+
raise DiaryGroupsUnreadable("unreadable")
|
|
253
|
+
monkeypatch.setattr(c, "_fetch_diary_groups", unreadable)
|
|
254
|
+
|
|
255
|
+
with pytest.raises(DiaryGroupsUnreadable):
|
|
256
|
+
c.diary_groups
|
|
257
|
+
assert c._diary_groups is None
|
|
258
|
+
|
|
259
|
+
def test_login_still_succeeds(self):
|
|
260
|
+
"""Reads must keep working; only diary-group lookups fail."""
|
|
261
|
+
c = CronometerClient(username="u", password="p")
|
|
262
|
+
resp = MagicMock()
|
|
263
|
+
resp.text = _without_string_type(build_settings_response(DEFAULT_ACCOUNT))
|
|
264
|
+
c.session.post = MagicMock(return_value=resp)
|
|
265
|
+
c.session.cookies = MagicMock()
|
|
266
|
+
c.session.cookies.get = MagicMock(return_value="new_nonce")
|
|
267
|
+
|
|
268
|
+
c._gwt_authenticate()
|
|
269
|
+
|
|
270
|
+
assert c.user_id == "0"
|
|
271
|
+
assert c._diary_groups is None
|
|
272
|
+
|
|
273
|
+
def test_write_tool_reports_error_without_writing(self, monkeypatch):
|
|
274
|
+
from cronometer_mcp import server
|
|
275
|
+
|
|
276
|
+
client = MagicMock()
|
|
277
|
+
type(client).diary_groups = property(
|
|
278
|
+
lambda self: (_ for _ in ()).throw(DiaryGroupsUnreadable("unreadable"))
|
|
279
|
+
)
|
|
280
|
+
monkeypatch.setattr(server, "_get_client", lambda: client)
|
|
281
|
+
|
|
282
|
+
result = json.loads(server.add_food_entry(
|
|
283
|
+
food_id=1, food_source_id=1, weight_grams=10,
|
|
284
|
+
date="2000-01-01", diary_group="Breakfast",
|
|
285
|
+
))
|
|
286
|
+
|
|
287
|
+
assert result["status"] == "error"
|
|
288
|
+
client.add_serving.assert_not_called()
|
|
289
|
+
|
|
290
|
+
|
|
154
291
|
def _client_with(settings: dict[str, str]):
|
|
155
292
|
groups = CronometerClient._parse_diary_groups(build_settings_response(settings))
|
|
156
293
|
client = MagicMock()
|
|
@@ -171,6 +308,17 @@ class TestResolveDiaryGroup:
|
|
|
171
308
|
assert _resolve_diary_group(_client_with(TEST_ACCOUNT), 0) == (0, None)
|
|
172
309
|
assert _resolve_diary_group(_client_with(TEST_ACCOUNT), "4") == (4, None)
|
|
173
310
|
|
|
311
|
+
@pytest.mark.parametrize("wire_index,selection", [
|
|
312
|
+
(2, 2), (2, "Lunch"), (3, 3), (3, "Dinner"),
|
|
313
|
+
])
|
|
314
|
+
def test_resolves_group_when_enable_setting_is_absent(
|
|
315
|
+
self, wire_index: int, selection: int | str,
|
|
316
|
+
) -> None:
|
|
317
|
+
settings = dict(TEST_ACCOUNT)
|
|
318
|
+
settings.pop(f"DG{wire_index + 1:02d}ON")
|
|
319
|
+
|
|
320
|
+
assert _resolve_diary_group(_client_with(settings), selection) == (wire_index, None)
|
|
321
|
+
|
|
174
322
|
@pytest.mark.parametrize("bad", [8, 9, -1, 99])
|
|
175
323
|
def test_rejects_out_of_range_index(self, bad):
|
|
176
324
|
"""Cronometer accepts these silently and the entry becomes unreachable."""
|
|
@@ -100,7 +100,7 @@ def test_servings_export_columns(test_day_exports):
|
|
|
100
100
|
def test_food_search_and_details(c):
|
|
101
101
|
hits = c.find_foods("egg")
|
|
102
102
|
assert hits and {"food_id", "food_source_id", "name"} <= hits[0].keys()
|
|
103
|
-
assert c.get_food(hits[0]["food_source_id"])
|
|
103
|
+
assert c.get_food(hits[0]["food_source_id"])["measures"]
|
|
104
104
|
|
|
105
105
|
|
|
106
106
|
def test_diary_groups_parse(c):
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|