cronometer-mcp 2.4.2__tar.gz → 2.4.3__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 (26) hide show
  1. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/PKG-INFO +1 -1
  2. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/cronometer_mcp/__init__.py +1 -1
  3. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/cronometer_mcp/client.py +87 -22
  4. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/pyproject.toml +1 -1
  5. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/server.json +2 -2
  6. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/tests/test_diary_groups.py +152 -4
  7. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/.github/workflows/drift.yml +0 -0
  8. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/.github/workflows/publish.yml +0 -0
  9. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/.gitignore +0 -0
  10. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/AGENTS.md +0 -0
  11. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/CLAUDE.md +0 -0
  12. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/LICENSE +0 -0
  13. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/README.md +0 -0
  14. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/RESEARCH-copy-repeat-gwt-rpc.md +0 -0
  15. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/SPEC-diary-groups.md +0 -0
  16. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/SPEC-streamable-http.md +0 -0
  17. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/cronometer_mcp/markdown.py +0 -0
  18. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/cronometer_mcp/server.py +0 -0
  19. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/release.sh +0 -0
  20. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/tests/__init__.py +0 -0
  21. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/tests/test_client.py +0 -0
  22. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/tests/test_drift.py +0 -0
  23. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/tests/test_live.py +0 -0
  24. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/tests/test_live_gate.py +0 -0
  25. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/tests/test_markdown.py +0 -0
  26. {cronometer_mcp-2.4.2 → cronometer_mcp-2.4.3}/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.2
3
+ Version: 2.4.3
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
@@ -1,6 +1,6 @@
1
1
  """Cronometer MCP Server — nutrition data from Cronometer via MCP."""
2
2
 
3
- __version__ = "2.4.2"
3
+ __version__ = "2.4.3"
4
4
 
5
5
  from .client import CronometerClient
6
6
  from .markdown import generate_food_log_md
@@ -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
 
@@ -360,6 +361,14 @@ class SessionExpiredError(RuntimeError):
360
361
  """Cronometer rejected the session (expired or logged out server-side)."""
361
362
 
362
363
 
364
+ class DiaryGroupsUnreadable(RuntimeError):
365
+ """The response carries diary group settings that could not be parsed.
366
+
367
+ Distinct from an account with no group settings: falling back to the
368
+ default meals here could enable a disabled group or rename one.
369
+ """
370
+
371
+
363
372
  class _GwtReader:
364
373
  """Read a GWT-RPC //OK response object by object, the way GWT does.
365
374
 
@@ -596,7 +605,13 @@ class CronometerClient:
596
605
 
597
606
  # The settings map in this same response carries the user's diary
598
607
  # groups. Parse it here so the fresh-login path costs no extra call.
599
- self._diary_groups = self._parse_diary_groups(resp.text)
608
+ # Unreadable groups must not fail the login: leave them unfetched so
609
+ # diary_groups re-fetches and raises on first use.
610
+ try:
611
+ self._diary_groups = self._parse_diary_groups(resp.text)
612
+ except DiaryGroupsUnreadable:
613
+ logger.warning("Diary group settings unreadable", exc_info=True)
614
+ self._diary_groups = None
600
615
 
601
616
  # Update nonce from cookies
602
617
  new_nonce = self._cookie_value("sesnonce")
@@ -1102,8 +1117,8 @@ class CronometerClient:
1102
1117
 
1103
1118
  Cronometer Gold exposes 8 diary group slots. They arrive as settings
1104
1119
  keys ``DG01``-``DG08`` (display names) alongside ``DG01ON``-``DG08ON``
1105
- (enable flags), inside the settings map the authenticate call already
1106
- returns.
1120
+ (optional enable flags), inside the settings map the authenticate call
1121
+ returns. An omitted enable flag leaves the named slot enabled.
1107
1122
 
1108
1123
  The wire ``diary_group`` value used by updateDiary is **0-based** over
1109
1124
  those slots, so ``DG01`` is wire index 0. On a default account the four
@@ -1121,43 +1136,92 @@ class CronometerClient:
1121
1136
  List of dicts ordered by wire index, each with ``wire_index``
1122
1137
  (int), ``settings_key`` (str), ``name`` (str) and ``enabled``
1123
1138
  (bool). Empty list if the response carries no DG keys.
1139
+
1140
+ Raises:
1141
+ DiaryGroupsUnreadable: DG keys are present but cannot be read.
1124
1142
  """
1143
+ dg_keys = [
1144
+ f"DG{slot:02d}{suffix}"
1145
+ for slot in range(1, DIARY_GROUP_SLOTS + 1)
1146
+ for suffix in ("", "ON")
1147
+ ]
1125
1148
  try:
1126
1149
  table = CronometerClient._extract_gwt_string_table(raw)
1127
1150
  except Exception:
1151
+ if '"DG0' in raw:
1152
+ raise DiaryGroupsUnreadable("string table unreadable")
1128
1153
  return []
1129
1154
  if not table:
1130
1155
  return []
1131
1156
 
1132
1157
  ref_of = {s: str(i + 1) for i, s in enumerate(table)}
1158
+ if not any(k in ref_of for k in dg_keys):
1159
+ return []
1133
1160
  body = raw[: raw.rindex('["')]
1134
1161
  tokens = [tok for tok in body.split(",") if tok.strip()]
1135
1162
 
1136
- def value_for(key: str) -> str | None:
1137
- ref = ref_of.get(key)
1138
- if ref is None:
1139
- return None
1140
- pos = next((i for i, tok in enumerate(tokens) if tok == ref), None)
1141
- if pos is None or pos < 2:
1142
- return None
1143
- tok = tokens[pos - 2]
1144
- if not tok.isdigit():
1145
- return None
1146
- i = int(tok)
1147
- return table[i - 1] if 0 < i <= len(table) else None
1163
+ string_type = next(
1164
+ (ref_of[s] for s in table if s.startswith("java.lang.String/")), None
1165
+ )
1166
+ if string_type is None:
1167
+ raise DiaryGroupsUnreadable("no java.lang.String type in the response")
1168
+
1169
+ positions: dict[str, list[int]] = {}
1170
+ for pos, tok in enumerate(tokens):
1171
+ positions.setdefault(tok, []).append(pos)
1172
+
1173
+ def occurrences(key: str) -> list[int]:
1174
+ return positions.get(ref_of.get(key, ""), [])
1175
+
1176
+ def is_entry_key(pos: int) -> bool:
1177
+ # A [String, value, String, key] settings entry.
1178
+ return (
1179
+ pos >= 3
1180
+ and tokens[pos - 1] == string_type
1181
+ and tokens[pos - 3] == string_type
1182
+ and tokens[pos - 2].isdigit()
1183
+ )
1184
+
1185
+ # Settings entries are four tokens wide, so every real key sits at the
1186
+ # same position mod 4. A value that happens to equal a DG key (a group
1187
+ # renamed "DG06") also looks like an entry key, but two tokens off that
1188
+ # phase. Take the phase most DG keys agree on; a tie is unreadable.
1189
+ phases = Counter(
1190
+ pos % 4 for k in dg_keys for pos in occurrences(k) if is_entry_key(pos)
1191
+ ).most_common(2)
1192
+ if not phases or (len(phases) == 2 and phases[0][1] == phases[1][1]):
1193
+ raise DiaryGroupsUnreadable("settings entry phase undecidable")
1194
+ phase = phases[0][0]
1195
+
1196
+ def lookup(key: str) -> tuple[set[str | None], bool]:
1197
+ """The key's settings values, and whether any occurrence is unexplained."""
1198
+ values: set[str | None] = set()
1199
+ unexplained = False
1200
+ for pos in occurrences(key):
1201
+ if pos % 4 == phase and is_entry_key(pos):
1202
+ i = int(tokens[pos - 2])
1203
+ values.add(table[i - 1] if 0 < i <= len(table) else None)
1204
+ elif not (pos % 4 == (phase + 2) % 4 and tokens[pos - 1] == string_type):
1205
+ unexplained = True # not another entry's value either
1206
+ return values, unexplained
1148
1207
 
1149
1208
  groups = []
1150
1209
  for slot in range(1, DIARY_GROUP_SLOTS + 1):
1151
1210
  key = f"DG{slot:02d}"
1152
- name = value_for(key)
1153
- if name is None:
1211
+ names, _ = lookup(key)
1212
+ if len(names) != 1 or None in names:
1154
1213
  continue
1214
+ flags, unexplained = lookup(f"{key}ON")
1155
1215
  groups.append({
1156
1216
  "wire_index": slot - 1,
1157
1217
  "settings_key": key,
1158
- "name": name,
1159
- "enabled": value_for(f"{key}ON") == "true",
1218
+ "name": names.pop(),
1219
+ # Only a flag missing from the response means enabled; one that
1220
+ # is unreadable or conflicting stays disabled (fail closed).
1221
+ "enabled": flags == {"true"} or (not flags and not unexplained),
1160
1222
  })
1223
+ if not groups:
1224
+ raise DiaryGroupsUnreadable("DG settings present but no group parsed")
1161
1225
  return groups
1162
1226
 
1163
1227
  def _fetch_diary_groups(self) -> list[dict]:
@@ -1186,9 +1250,10 @@ class CronometerClient:
1186
1250
  restored session fetches lazily on first access, so callers that never
1187
1251
  touch diary groups never pay for it.
1188
1252
 
1189
- Falls back to the four default meals at wire 1-4 if nothing could be
1190
- parsed, so a parse regression degrades to the legacy behavior rather
1191
- than blocking every write. A failed fetch (timeout, dead session) is
1253
+ Falls back to the four default meals at wire 1-4 only when the
1254
+ response carries no DG settings at all. DG settings that are present
1255
+ but unreadable raise DiaryGroupsUnreadable instead (not cached, so the
1256
+ next access retries): the defaults could enable a disabled group. A failed fetch (timeout, dead session) is
1192
1257
  not a parse regression: it raises and is retried on the next access,
1193
1258
  since the defaults would send writes to the wrong group on an account
1194
1259
  with custom groups.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "cronometer-mcp"
7
- version = "2.4.2"
7
+ version = "2.4.3"
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.2",
9
+ "version": "2.4.3",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "pypi",
13
13
  "identifier": "cronometer-mcp",
14
- "version": "2.4.2",
14
+ "version": "2.4.3",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -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] = ["java.lang.String/2004016611"]
30
- # pad so the type ref lands on 54, matching the real payload's layout
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."""
File without changes
File without changes
File without changes
File without changes