@cyanheads/openfoodfacts-mcp-server 0.4.4 → 0.5.0
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.
- package/AGENTS.md +7 -1
- package/CLAUDE.md +7 -1
- package/README.md +18 -17
- package/changelog/0.4.x/0.4.5.md +39 -0
- package/changelog/0.5.x/0.5.0.md +31 -0
- package/dist/mcp-server/tools/definitions/compare-products.tool.d.ts +14 -0
- package/dist/mcp-server/tools/definitions/compare-products.tool.d.ts.map +1 -1
- package/dist/mcp-server/tools/definitions/compare-products.tool.js +62 -18
- package/dist/mcp-server/tools/definitions/compare-products.tool.js.map +1 -1
- package/dist/mcp-server/tools/definitions/get-product.tool.d.ts +17 -0
- package/dist/mcp-server/tools/definitions/get-product.tool.d.ts.map +1 -1
- package/dist/mcp-server/tools/definitions/get-product.tool.js +160 -74
- package/dist/mcp-server/tools/definitions/get-product.tool.js.map +1 -1
- package/dist/mcp-server/tools/definitions/index.d.ts +31 -12
- package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -1
- package/dist/mcp-server/tools/definitions/search-products.tool.d.ts +9 -12
- package/dist/mcp-server/tools/definitions/search-products.tool.d.ts.map +1 -1
- package/dist/mcp-server/tools/definitions/search-products.tool.js +392 -227
- package/dist/mcp-server/tools/definitions/search-products.tool.js.map +1 -1
- package/dist/mcp-server/tools/read-source.d.ts +17 -4
- package/dist/mcp-server/tools/read-source.d.ts.map +1 -1
- package/dist/mcp-server/tools/read-source.js +41 -4
- package/dist/mcp-server/tools/read-source.js.map +1 -1
- package/dist/mcp-server/tools/record-metadata.d.ts +41 -0
- package/dist/mcp-server/tools/record-metadata.d.ts.map +1 -0
- package/dist/mcp-server/tools/record-metadata.js +61 -0
- package/dist/mcp-server/tools/record-metadata.js.map +1 -0
- package/dist/services/mirror/mirror-feeds.d.ts +4 -3
- package/dist/services/mirror/mirror-feeds.d.ts.map +1 -1
- package/dist/services/mirror/mirror-feeds.js +2 -1
- package/dist/services/mirror/mirror-feeds.js.map +1 -1
- package/dist/services/mirror/mirror-ingester.d.ts +6 -1
- package/dist/services/mirror/mirror-ingester.d.ts.map +1 -1
- package/dist/services/mirror/mirror-ingester.js +43 -12
- package/dist/services/mirror/mirror-ingester.js.map +1 -1
- package/dist/services/mirror/mirror-queries.d.ts +15 -5
- package/dist/services/mirror/mirror-queries.d.ts.map +1 -1
- package/dist/services/mirror/mirror-queries.js +34 -7
- package/dist/services/mirror/mirror-queries.js.map +1 -1
- package/dist/services/mirror/mirror-store.d.ts +13 -2
- package/dist/services/mirror/mirror-store.d.ts.map +1 -1
- package/dist/services/mirror/mirror-store.js +13 -3
- package/dist/services/mirror/mirror-store.js.map +1 -1
- package/dist/services/mirror/mirror-sync.d.ts.map +1 -1
- package/dist/services/mirror/mirror-sync.js +5 -1
- package/dist/services/mirror/mirror-sync.js.map +1 -1
- package/dist/services/mirror/record-builder.d.ts +28 -17
- package/dist/services/mirror/record-builder.d.ts.map +1 -1
- package/dist/services/mirror/record-builder.js +227 -113
- package/dist/services/mirror/record-builder.js.map +1 -1
- package/dist/services/openfoodfacts/openfoodfacts-service.d.ts +165 -114
- package/dist/services/openfoodfacts/openfoodfacts-service.d.ts.map +1 -1
- package/dist/services/openfoodfacts/openfoodfacts-service.js +447 -309
- package/dist/services/openfoodfacts/openfoodfacts-service.js.map +1 -1
- package/dist/services/openfoodfacts/types.d.ts +80 -51
- package/dist/services/openfoodfacts/types.d.ts.map +1 -1
- package/dist/services/openfoodfacts/types.js +14 -19
- package/dist/services/openfoodfacts/types.js.map +1 -1
- package/dist/services/taxonomy/brand-keys.d.ts +35 -0
- package/dist/services/taxonomy/brand-keys.d.ts.map +1 -0
- package/dist/services/taxonomy/brand-keys.js +52 -0
- package/dist/services/taxonomy/brand-keys.js.map +1 -0
- package/dist/services/taxonomy/brand-synonyms.d.ts +12 -0
- package/dist/services/taxonomy/brand-synonyms.d.ts.map +1 -0
- package/dist/services/taxonomy/brand-synonyms.js +208 -0
- package/dist/services/taxonomy/brand-synonyms.js.map +1 -0
- package/dist/services/taxonomy/tag-id.d.ts +18 -0
- package/dist/services/taxonomy/tag-id.d.ts.map +1 -0
- package/dist/services/taxonomy/tag-id.js +62 -0
- package/dist/services/taxonomy/tag-id.js.map +1 -0
- package/dist/services/taxonomy/taxonomy-service.d.ts +54 -27
- package/dist/services/taxonomy/taxonomy-service.d.ts.map +1 -1
- package/dist/services/taxonomy/taxonomy-service.js +83 -58
- package/dist/services/taxonomy/taxonomy-service.js.map +1 -1
- package/dist/utils/until-cancelled.d.ts +11 -0
- package/dist/utils/until-cancelled.d.ts.map +1 -0
- package/dist/utils/until-cancelled.js +19 -0
- package/dist/utils/until-cancelled.js.map +1 -0
- package/package.json +6 -5
- package/server.json +3 -3
- package/skills/openfoodfacts-guide/SKILL.md +9 -9
- package/dist/services/openfoodfacts/analyzer-stop-words.d.ts +0 -70
- package/dist/services/openfoodfacts/analyzer-stop-words.d.ts.map +0 -1
- package/dist/services/openfoodfacts/analyzer-stop-words.js +0 -571
- package/dist/services/openfoodfacts/analyzer-stop-words.js.map +0 -1
package/AGENTS.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Developer Protocol
|
|
2
2
|
|
|
3
3
|
**Server:** openfoodfacts-mcp-server
|
|
4
|
-
**Version:** 0.
|
|
4
|
+
**Version:** 0.5.0
|
|
5
5
|
**Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.13.22`
|
|
6
6
|
**Engines:** Bun ≥1.4.4, Node ≥24.0.0
|
|
7
7
|
**MCP SDK:** `@modelcontextprotocol/server` ^2.4.0
|
|
@@ -216,10 +216,15 @@ src/
|
|
|
216
216
|
types.ts # Domain types
|
|
217
217
|
taxonomy/
|
|
218
218
|
taxonomy-service.ts # Tag vocabulary — live resolution, offline sample, merge/fallback policy, tag-value canonicalization
|
|
219
|
+
brand-keys.ts # Brand keys: brandSlug, brandKey, brandKeys (a brand's key plus the keys of its brands.txt entry's other names), shared by the mirror and every search path
|
|
220
|
+
brand-synonyms.ts # Brand synonym groups from brands.txt — generated by `bun run brands:sync`, never hand-edited
|
|
221
|
+
tag-id.ts # Product Opener's tag ID builder, ported (no service dependency)
|
|
219
222
|
utils/
|
|
220
223
|
markdown.ts # Contextual Markdown escaping for crowd-sourced values in content[]
|
|
224
|
+
until-cancelled.ts # Wait on shared work as one caller: its answer, or that caller's own cancellation
|
|
221
225
|
mcp-server/
|
|
222
226
|
tools/read-source.ts # How tool text names an answer's source (off_api / off_mirror) and the mirror freshness note
|
|
227
|
+
tools/record-metadata.ts # Completeness label and the created / last-modified lines every product tool renders
|
|
223
228
|
tools/definitions/
|
|
224
229
|
get-product.tool.ts # off_get_product
|
|
225
230
|
search-products.tool.ts # off_search_products
|
|
@@ -321,6 +326,7 @@ When you complete a skill's checklist, check the boxes and add a completion time
|
|
|
321
326
|
| `bun run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior |
|
|
322
327
|
| `bun run test` | Run tests (Vitest — use `bun run test`, not `bun test`) |
|
|
323
328
|
| `bun run mirror:init` / `mirror:refresh` / `mirror:status` / `mirror:verify` | Build, refresh, inspect, and integrity-check the local export mirror at `OFF_MIRROR_PATH` (checkout or Docker image) |
|
|
329
|
+
| `bun run brands:sync [<40-char sha>]` | Regenerate `src/services/taxonomy/brand-synonyms.ts` from openfoodfacts-server `taxonomies/brands.txt` at one commit: the full lowercase SHA given, or with no argument the commit the module header names. Writes nothing when two entries claim one brand key or a computed entry ID is missing from `static.openfoodfacts.org/data/taxonomies/brands.json` |
|
|
324
330
|
| `bun run start:stdio` | Production mode (stdio) |
|
|
325
331
|
| `bun run start:http` | Production mode (HTTP) |
|
|
326
332
|
| `bun run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
|
package/CLAUDE.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Developer Protocol
|
|
2
2
|
|
|
3
3
|
**Server:** openfoodfacts-mcp-server
|
|
4
|
-
**Version:** 0.
|
|
4
|
+
**Version:** 0.5.0
|
|
5
5
|
**Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.13.22`
|
|
6
6
|
**Engines:** Bun ≥1.4.4, Node ≥24.0.0
|
|
7
7
|
**MCP SDK:** `@modelcontextprotocol/server` ^2.4.0
|
|
@@ -216,10 +216,15 @@ src/
|
|
|
216
216
|
types.ts # Domain types
|
|
217
217
|
taxonomy/
|
|
218
218
|
taxonomy-service.ts # Tag vocabulary — live resolution, offline sample, merge/fallback policy, tag-value canonicalization
|
|
219
|
+
brand-keys.ts # Brand keys: brandSlug, brandKey, brandKeys (a brand's key plus the keys of its brands.txt entry's other names), shared by the mirror and every search path
|
|
220
|
+
brand-synonyms.ts # Brand synonym groups from brands.txt — generated by `bun run brands:sync`, never hand-edited
|
|
221
|
+
tag-id.ts # Product Opener's tag ID builder, ported (no service dependency)
|
|
219
222
|
utils/
|
|
220
223
|
markdown.ts # Contextual Markdown escaping for crowd-sourced values in content[]
|
|
224
|
+
until-cancelled.ts # Wait on shared work as one caller: its answer, or that caller's own cancellation
|
|
221
225
|
mcp-server/
|
|
222
226
|
tools/read-source.ts # How tool text names an answer's source (off_api / off_mirror) and the mirror freshness note
|
|
227
|
+
tools/record-metadata.ts # Completeness label and the created / last-modified lines every product tool renders
|
|
223
228
|
tools/definitions/
|
|
224
229
|
get-product.tool.ts # off_get_product
|
|
225
230
|
search-products.tool.ts # off_search_products
|
|
@@ -321,6 +326,7 @@ When you complete a skill's checklist, check the boxes and add a completion time
|
|
|
321
326
|
| `bun run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior |
|
|
322
327
|
| `bun run test` | Run tests (Vitest — use `bun run test`, not `bun test`) |
|
|
323
328
|
| `bun run mirror:init` / `mirror:refresh` / `mirror:status` / `mirror:verify` | Build, refresh, inspect, and integrity-check the local export mirror at `OFF_MIRROR_PATH` (checkout or Docker image) |
|
|
329
|
+
| `bun run brands:sync [<40-char sha>]` | Regenerate `src/services/taxonomy/brand-synonyms.ts` from openfoodfacts-server `taxonomies/brands.txt` at one commit: the full lowercase SHA given, or with no argument the commit the module header names. Writes nothing when two entries claim one brand key or a computed entry ID is missing from `static.openfoodfacts.org/data/taxonomies/brands.json` |
|
|
324
330
|
| `bun run start:stdio` | Production mode (stdio) |
|
|
325
331
|
| `bun run start:http` | Production mode (HTTP) |
|
|
326
332
|
| `bun run changelog:build` | Regenerate `CHANGELOG.md` from `changelog/*.md` |
|
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
<div align="center">
|
|
9
9
|
|
|
10
|
-
[](./CHANGELOG.md) [](./LICENSE) [](https://github.com/users/cyanheads/packages/container/package/openfoodfacts-mcp-server) [](https://modelcontextprotocol.io/) [](https://www.npmjs.com/package/@cyanheads/openfoodfacts-mcp-server) [](https://www.typescriptlang.org/) [](https://bun.sh/)
|
|
11
11
|
|
|
12
12
|
</div>
|
|
13
13
|
|
|
@@ -50,22 +50,22 @@ Packaged-food data from Open Food Facts, a crowd-sourced database of 3M+ product
|
|
|
50
50
|
|
|
51
51
|
### `off_get_product` <sub>tool</sub>
|
|
52
52
|
|
|
53
|
-
- `barcode` is digits only, 4–40 digits after any leading zeros; optional `fields` trims the response and pulls in what a field depends on (`nutriments` brings the serving size, quantity, and unit, and `serving_quantity` and `serving_quantity_unit` each bring the other plus the serving size), with `requested_fields` echoing what was fetched
|
|
54
|
-
- Returns `product_name` and `generic_name` (what the product is, in its main language), ingredients (raw text
|
|
53
|
+
- `barcode` is digits only, 4–40 digits after any leading zeros; optional `fields` trims the response and pulls in what a field depends on (`nutriments` brings the serving size, quantity, and unit, and `serving_quantity` and `serving_quantity_unit` each bring the other plus the serving size; `ingredients_text` and `ingredients_text_languages` each bring `lang`), with `requested_fields` echoing what was fetched
|
|
54
|
+
- Returns `product_name` and `generic_name` (what the product is, in its main language), ingredients (raw text in the record's main language, named by `lang`, which can be a contributor's translation; `ingredients_text_languages` with the text in every language entered; the `image_ingredients_url` and `image_nutrition_url` label photos to check it against; and a parsed tree up to three levels deep with `percent_estimate`), `allergens_tags`, `traces_tags`, `additives_tags`, `ingredients_analysis_tags` (vegan, vegetarian, palm-oil verdicts), `nutriscore_grade` with `nutriscore_score` (the points behind it, which rank products of one kind only), `nova_group`, `ecoscore_grade` (Green-Score) with `ecoscore_score`, `nutrient_levels` (Open Food Facts' low, moderate, or high for fat, saturated fat, sugars, and salt, with a `basis` of `as_sold` or `prepared` naming the figures it judged; `fields: ["nutrient_levels"]` brings `nutriments` for that reason), `nutriments` (per serving, and per 100 g, or per 100 ml for liquids; `carbohydrates_100g` and the separate `carbohydrates_total_100g`, which includes fiber, are different nutrients and never derived from each other), category/label/packaging/origin/country tags, `image_url`, `completeness` (it can exceed 1), and `last_modified` and `created` as ISO 8601 times
|
|
55
55
|
- `traces_tags: ["en:none"]` means the label states no traces, while an empty array means none entered yet; a barcode no contributor has recorded fails as `not_found`
|
|
56
56
|
- Open Food Facts returns one preparation state of the nutrition per read. A read of prepared-product figures puts them under keys ending in `_prepared` in `additional_100g` and `additional_serving`, and prints them in "as prepared" sections. When a read returns only prepared figures, one more product read fetches the single as-sold set the record stores (`/api/v3.5` `fields=nutrition.input_sets`) and fills the named as-sold fields per 100 g, or per 100 ml for liquids, with no as-sold per-serving figure; `nutriments.stored_as_sold` reports `read`, `none` (the record stores no usable set), or `unread` with a `reason`, an `error`, and, when the failure named a wait, `retryAfter` in whole seconds (the call itself still succeeds). Other reads send nothing extra
|
|
57
|
-
- `source` (`off_api` or `off_mirror`) names where the product was read; a barcode a [local mirror](#local-export-mirror) holds is read from it with no upstream request, with `mirror_as_of` (the time up to which the copy reflects every product contributed or edited on Open Food Facts) and a `mirror_snapshot` note, and the stored as-sold set comes from the same stored record
|
|
57
|
+
- `source` (`off_api` or `off_mirror`) names where the product was read; a barcode a [local mirror](#local-export-mirror) holds is read from it with no upstream request, with `mirror_as_of` (the time up to which the copy reflects every product contributed or edited on Open Food Facts) and a `mirror_snapshot` note, and the stored as-sold set comes from the same stored record; a row the copy holds from before it stored a requested field reads live for it, and `mirror_fields_unread` names what a failed or empty live read left out
|
|
58
58
|
|
|
59
59
|
---
|
|
60
60
|
|
|
61
61
|
### `off_search_products` <sub>tool</sub>
|
|
62
62
|
|
|
63
|
-
- `query` (up to 24 words, all of which must match the name
|
|
63
|
+
- `query` (up to 24 words, all of which must match the product name or generic name only, since category, label, and brand wording belongs in the tag filters; punctuation separates words, so `milk-chocolate` requires both) plus the tag filters `categories_tag`, `brands_tag`, `labels_tag` (up to 10), `allergens_tag`, `traces_tag`, `ingredients_analysis_tag`, `ingredients_tag` (up to 10, all of which must appear), `additives_tag`, `nutrition_grade`, `nova_group`, `ecoscore_grade` (Green-Score), `countries_tag`, the `exclude_allergens` / `exclude_traces` lists (up to 14 each), and up to 18 `nutrient_filters` (per 100 g, or per 100 ml for liquids), all combined as AND; optional `sort_by`
|
|
64
64
|
- `nutrition_grade`, `nova_group`, and `ecoscore_grade` each take one grade or an array matching any of them (`["a", "b"]` for Nutri-Score B or better), where a `labels_tag` array requires all of its values; `ecoscore_grade` `a` excludes `a-plus`. A grade filter never changes which backend answers; on a text search it matches the grades the index holds, which each row shows. A tag-only `ecoscore_grade` search matches the grade Open Food Facts files for France, while each row shows the world grade
|
|
65
|
-
- `page_size` defaults to 20 and is served at up to 100 per call; a larger value, with no ceiling, is served at 100 and flagged in `page_size_capped`, and `page` counts pages of 100. Rows carry `barcode`, `product_name`, `brands`, `nutriscore_grade`, `nova_group`, `ecoscore_grade`,
|
|
66
|
-
-
|
|
65
|
+
- `page_size` defaults to 20 and is served at up to 100 per call; a larger value, with no ceiling, is served at 100 and flagged in `page_size_capped`, and `page` counts pages of 100. Rows carry `barcode`, `product_name`, `brands`, `quantity` (which tells pack sizes of one product apart), `nutriscore_grade`, `nova_group`, `ecoscore_grade`, `categories_tags`, `completeness`, and `last_modified` and `created` as ISO 8601 times (on a text search, the indexed revision's), plus `total`, `total_is_lower_bound`, `last_page`, `omitted`, and `truncated` (more matches beyond this page). Exclusions add `exclusion_coverage`, since products with no allergen data entered pass them; `nutrient_filters` add `indexed_nutriments` (the index values the filters were compared against, which can differ from `off_get_product`)
|
|
66
|
+
- Each `nutrient_filters` bound is sent as given and compared as a decimal (`sugars gt 3.5` excludes 3.5 and keeps 3.6), for all nine nutrients. A constraint reaches only records whose text-index entry carries that nutrient, and many entries carry none even when the record `off_get_product` reads has them, so a product meeting the constraint can be missing and an empty result does not show that none exists
|
|
67
67
|
- `ingredients_tag` takes canonical ingredient IDs (`en:inulin`; resolve one with `off_browse_taxonomy` facet `ingredients`, where IDs are singular), and each parsed ingredient also carries its taxonomy parents, so `en:vegetable` matches a product listing carrot. It is answered only by the text index, with or without `query`, since the mirror indexes no ingredients and the live tag path stops at page 10
|
|
68
|
-
- `query`, `nutrient_filters`, or `ingredients_tag` searches a text index that lags the live database (flagged in `text_index_snapshot`), reaches only the first 10,000 results, and
|
|
68
|
+
- `query`, `nutrient_filters`, or `ingredients_tag` searches a text index that lags the live database (flagged in `text_index_snapshot` and dated by `text_index_as_of`, the time of the newest record the index holds, when this server could read it), reaches only the first 10,000 results, and combines with `additives_tag`; tag-only searches read the live database through page 10, unless a [local mirror](#local-export-mirror) serves them: with every tag value confirmed (a brand counts when the mirror holds products under any of its keys), a mirror-served search has an exact `total` and reaches its first 10,000 results, one carrying `ecoscore_grade` is served only once a full reload of the mirror has indexed Green-Score, and one carrying `brands_tag` only once a full reload has keyed every brand. A page past any of these limits fails as `page_out_of_range`; for a brand the mirror holds no product under, page 11 or later sends one live count, which answers a page the live matches end before as empty with that total and refuses one they reach into, naming the brand and the live total
|
|
69
69
|
- `source` (`off_api` or `off_mirror`) names where the answer was read; from the mirror it also carries `mirror_as_of` and a `mirror_snapshot` note, and the default order and `sort_by` `popularity_key` and `unique_scans_n` follow the values stored with each record, which can differ from a live search, which ranks by its current scan counts
|
|
70
70
|
|
|
71
71
|
---
|
|
@@ -73,9 +73,9 @@ Packaged-food data from Open Food Facts, a crowd-sourced database of 3M+ product
|
|
|
73
73
|
### `off_compare_products` <sub>tool</sub>
|
|
74
74
|
|
|
75
75
|
- 2–100 `barcodes`, one row each in input order; repeated barcodes are compared once, and those past the 10th distinct one are listed in `unprocessed` without being fetched
|
|
76
|
-
- Rows carry `found`, `nutriscore_grade`, `nova_group`, `ecoscore_grade
|
|
76
|
+
- Rows carry `found`, `nutriscore_grade` and `nutriscore_score`, `nova_group`, `ecoscore_grade` and `ecoscore_score` (the points behind each grade; Nutri-Score points break a grade tie only between products of one kind), energy, fat, saturated fat, carbohydrates, `carbohydrates_total_100g` (total carbohydrates including fiber, a separate nutrient), sugars, salt, protein, and fiber (per 100 g, or per 100 ml for liquids), and `completeness`; missing values stay absent, never imputed
|
|
77
77
|
- A read of prepared-product figures adds a `prepared` object on the row with the same columns, read from the `*_prepared_100g` keys and never substituted for an as-sold figure. A row whose read returned only prepared figures gets the same stored as-sold read as `off_get_product`, once every barcode's product read has settled, and reports it as `stored_as_sold` (`read`, `none`, or `unread`, which never moves the barcode into `failed`). A row with as-sold figures appears in the as-sold table, a row with `prepared` in the "as prepared" table, and a row with both appears in both
|
|
78
|
-
- Each row carries `source` (`off_api` or `off_mirror`), and `mirror_as_of` for a row read from a [local mirror](#local-export-mirror), so one comparison can mix the two; a `mirror_snapshot` note appears when any row came from it
|
|
78
|
+
- Each row carries `source` (`off_api` or `off_mirror`), and `mirror_as_of` for a row read from a [local mirror](#local-export-mirror), so one comparison can mix the two; a `mirror_snapshot` note appears when any row came from it. A mirror row stored before the score points existed is served as stored with no live read, and `mirror_fields_unread` on the row names what it lacks
|
|
79
79
|
- `not_found` lists barcodes with no contributor record and `failed` lists fetches that failed, each with a `reason` and, when the failure named a wait, `retryAfter` in whole seconds; a failed barcode gets no row and never blocks the rest
|
|
80
80
|
|
|
81
81
|
---
|
|
@@ -95,16 +95,16 @@ Open Food Facts-specific:
|
|
|
95
95
|
- No API key; the identifying `User-Agent` Open Food Facts' terms require is built in
|
|
96
96
|
- Per-endpoint request budgets (product 15/min, search 10/min, taxonomy 10/min); transient failures retry up to 4 attempts within a total deadline of 35 s for a product or search read and 20 s for a taxonomy lookup (one caller's search that canonicalizes a tag first can spend 55 s), after which the read fails as `upstream_timeout`, or `rate_limited` when its last finished attempt answered 429
|
|
97
97
|
- The stored as-sold read for a prepared-only product spends the product budget, so a barcode can take two product reads, and has its own 20 s deadline: a call settles within 35 s + 20 s = 55 s, and an unread set never fails the call or the row
|
|
98
|
-
- Optional [local export mirror](#local-export-mirror) (`OFF_MIRROR_PATH`): barcode reads and confirmed tag-only searches served from a SQLite copy of the export,
|
|
98
|
+
- Optional [local export mirror](#local-export-mirror) (`OFF_MIRROR_PATH`): barcode reads and confirmed tag-only searches served from a SQLite copy of the export that daily deltas update with contributor edits and a full reload, about every 30 days, updates with recomputed values and removals; a result names its `source` and, from the mirror, the time it reflects edits through
|
|
99
99
|
- Nutriments normalized from hyphenated keys (`energy-kcal_100g` → `energy_kcal_100g`), with `additional_100g` / `additional_serving` maps that label each nutrient with its unit
|
|
100
|
-
- Tag filters take canonical IDs (`en:organic`, `en:no-gluten`); on text searches a case variant
|
|
100
|
+
- Tag filters take canonical IDs (`en:organic`, `en:no-gluten`); on text searches a case variant or synonym is canonicalized first (`US` → `en:united-states`), while `brands_tag` takes a brand name or slug, slugged the way Open Food Facts slugs it (`Nestlé` → `nestle`) and matched together with every other name its Open Food Facts brand entry lists (`7-Up`, `7up`, and `Seven Up` match the same products), on every search path
|
|
101
101
|
- Every field is contributor-entered, so a missing one means not yet recorded, except that a product read returning only prepared-product nutrition is followed by a read of the as-sold figures the record stores, reported as `stored_as_sold`; Nutri-Score, NOVA, and Green-Score are Open Food Facts' own computed grades, returned as-is, and carry regional formula caveats
|
|
102
102
|
|
|
103
103
|
Agent-friendly output:
|
|
104
104
|
|
|
105
105
|
- Per-serving nutrition carries its denominator: `serving_size`, `serving_quantity`, `serving_quantity_unit`, and a note when none is recorded
|
|
106
106
|
- Graceful partial failure: `off_compare_products` returns resolved rows alongside `not_found` and `failed`
|
|
107
|
-
- Explicit count bounds: `total_is_lower_bound`, `last_page`,
|
|
107
|
+
- Explicit count bounds: `total_is_lower_bound`, `last_page`, and `omitted` on searches
|
|
108
108
|
- Typed failures: each carries a declared `reason` (`upstream_error`, `upstream_timeout`, `upstream_rejected`, `rate_limited`, plus per-tool input reasons) and a recovery hint; an incomplete upstream response is a retryable `upstream_error`, or `upstream_timeout` when search flags a timeout, never an empty result or a not-found
|
|
109
109
|
|
|
110
110
|
## Getting started
|
|
@@ -142,7 +142,7 @@ No API key or account is needed: the server identifies itself to Open Food Facts
|
|
|
142
142
|
|:---------|:------------|:--------|
|
|
143
143
|
| `OFF_BASE_URL` | Open Food Facts API base URL. | `https://world.openfoodfacts.org` |
|
|
144
144
|
| `OFF_RATE_LIMIT_PRODUCT` | Product read budget (requests/min). The default is Open Food Facts' published per-IP limit; lower it on a shared outbound IP. | `15` |
|
|
145
|
-
| `OFF_RATE_LIMIT_SEARCH` | Search budget (requests/min). The default is Open Food Facts' published per-IP limit. | `10` |
|
|
145
|
+
| `OFF_RATE_LIMIT_SEARCH` | Search budget (requests/min). The default is Open Food Facts' published per-IP limit. The text index date probe behind `text_index_as_of` draws on it only while two slots are free, and each probe (at most one per 6 hours, or per 15 minutes while it keeps failing) counts against it. | `10` |
|
|
146
146
|
| `OFF_RATE_LIMIT_TAXONOMY` | Taxonomy lookup budget (requests/min), shared by `off_browse_taxonomy`, tag canonicalization on text searches, and exclusion checks. | `10` |
|
|
147
147
|
| `OFF_MIRROR_PATH` | Path of the [local export mirror](#local-export-mirror)'s SQLite file. Unset disables the mirror. Works from a source checkout or the Docker image only. | unset |
|
|
148
148
|
| `MCP_TRANSPORT_TYPE` | Transport: `stdio` or `http`. | `stdio` |
|
|
@@ -198,7 +198,7 @@ The image defaults to HTTP transport, stateless session mode, and logs to `/var/
|
|
|
198
198
|
|
|
199
199
|
#### Local export mirror
|
|
200
200
|
|
|
201
|
-
Setting `OFF_MIRROR_PATH` keeps a local SQLite copy of the Open Food Facts export. `off_get_product` and `off_compare_products` read it first by barcode and read live for a barcode it lacks. A search by tag filters alone is served from it when every value is a confirmed tag
|
|
201
|
+
Setting `OFF_MIRROR_PATH` keeps a local SQLite copy of the Open Food Facts export. `off_get_product` and `off_compare_products` read it first by barcode and read live for a barcode it lacks. A search by tag filters alone is served from it when every value is a confirmed tag and a brand is one the copy holds products under in any of its keys (its slug and the other names of its Open Food Facts brand entry), with an exact `total` through its first 10,000 results, a search carrying `ecoscore_grade` only once a full reload has indexed Green-Score, and one carrying `brands_tag` only once a full reload built at record version 4 has completed, so brand searches read live until then; every other search is live. The copy reflects contributor edits through `mirror_as_of`; computed values (grades, nutrient levels, ingredient analysis, additives, allergens and traces, completeness, data-quality tags) reach it with the record's next edit or the next full reload, and a removed product only with that reload, so a search matches the values stored with each record. A product read of a row not yet rewritten by that reload is live too for any requested field the row lacks (`generic_name`, `nutrient_levels`, the ingredient languages, the score points, and the label photos); should that read fail or find no product, the row answers without them and `mirror_fields_unread` says why. `off_compare_products` stays on the mirror through a reload and serves such a row as stored, its `mirror_fields_unread` naming the fields it lacks. Record dates come from the row at any record version. A store error falls through to a live read. The mirror scripts need a checkout or the Docker image, so the npm install and `.mcpb` bundle stay live-only.
|
|
202
202
|
|
|
203
203
|
In the image, mount a volume at the store directory, `/usr/src/app/.mirror`, set `OFF_MIRROR_PATH` to a file in it, and build the store once with `docker exec`:
|
|
204
204
|
|
|
@@ -214,7 +214,7 @@ docker exec openfoodfacts-mcp-server bun run mirror:verify # status plus SQLit
|
|
|
214
214
|
docker exec openfoodfacts-mcp-server bun run mirror:refresh # one delta pass by hand
|
|
215
215
|
```
|
|
216
216
|
|
|
217
|
-
A full `mirror:init` of the 4.9M-product export took about 1 h 48 min in testing, peaked at about 27 GB on the volume while the 13.4 GB download sat beside the store, left a 14.3 GB store, and used under 350 MB of memory. Reads stay live until `mirror:init` completes. Once `OFF_MIRROR_PATH` is set the server refreshes the mirror itself every three hours, at minute 30 of the server's local time: it applies each new daily delta, and reloads the whole export when the last full load is 30 days old and the export has changed since, because deltas never
|
|
217
|
+
A full `mirror:init` of the 4.9M-product export took about 1 h 48 min in testing, peaked at about 27 GB on the volume while the 13.4 GB download sat beside the store, left a 14.3 GB store, and used under 350 MB of memory. Reads stay live until `mirror:init` completes. Once `OFF_MIRROR_PATH` is set the server refreshes the mirror itself every three hours, at minute 30 of the server's local time: it applies each new daily delta, and reloads the whole export when the last full load is 30 days old and the export has changed since, because deltas select records by their last edit, so they never carry a deleted product or a value Open Food Facts recomputes without an edit (grades, ingredient analysis, allergens, completeness, and the rest the `mirror_snapshot` note names), and whenever the last full load was built by an older record version, which a release changing what a record holds bumps. An export or delta line that is not valid JSON, or runs past 16 MiB, is skipped and logged by line number, and `mirror:status` prints how many the last full load skipped. An export that builds no product at all is refused before it deletes anything (`export_no_products`): the mirror keeps serving what it holds, and each refresh downloads the export again, applying no delta, until an export that lists products replaces it. While a reload runs, `mirror_as_of` can drop below the last delta's end, to a time the rewritten products reflect, until the load completes and the deltas re-apply. `mirror:status` and `mirror:verify` exit non-zero unless a sync has completed and the store holds products. From a checkout, run the same `bun run mirror:*` scripts with `OFF_MIRROR_PATH` set in `.env`.
|
|
218
218
|
|
|
219
219
|
## Project structure
|
|
220
220
|
|
|
@@ -226,7 +226,8 @@ A full `mirror:init` of the 4.9M-product export took about 1 h 48 min in testing
|
|
|
226
226
|
| `src/services/openfoodfacts` | Open Food Facts API client — HTTP, rate limiting, retry, field normalization. |
|
|
227
227
|
| `src/services/mirror` | Local export mirror — SQLite store, record builder, export and delta ingester, tag-search queries, and the refresh schedule. |
|
|
228
228
|
| `scripts/mirror-*.ts` | `mirror:init`, `mirror:refresh`, `mirror:status`, and `mirror:verify`. |
|
|
229
|
-
| `
|
|
229
|
+
| `scripts/brands-sync.ts` | `brands:sync`, which regenerates the brand synonym table from Open Food Facts' brands taxonomy. |
|
|
230
|
+
| `src/services/taxonomy` | Tag vocabulary — live resolution, offline sample, tag-value canonicalization, and brand keys. |
|
|
230
231
|
| `src/utils` | Markdown escaping for contributor-entered values in text output. |
|
|
231
232
|
| `skills/` | Published Agent Skills for the agents that call the tools. |
|
|
232
233
|
| `tests/` | Unit and integration tests mirroring `src/`. |
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
---
|
|
2
|
+
summary: "off_get_product returns the ingredients text in every language with the label photos, score points, and record dates; off_search_products rows add quantity, completeness, and dates and the text index is dated; brand names with accents match; total carbohydrates are reported as their own nutrient."
|
|
3
|
+
breaking: false
|
|
4
|
+
security: false
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# 0.4.5 — 2026-11-24
|
|
8
|
+
|
|
9
|
+
## Added
|
|
10
|
+
|
|
11
|
+
- **`lang`, `ingredients_text_languages`, `image_ingredients_url`, `image_nutrition_url`** ([#91](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/91)): `off_get_product` names the record's main language, returns the ingredients text in every language entered (empty entries left out), and links the ingredients and nutrition photos to check it against. All four are `fields` values, and `ingredients_text` and `ingredients_text_languages` each bring `lang`.
|
|
12
|
+
- **`nutriscore_score`, `ecoscore_score`** ([#93](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/93)): the points behind each grade, on `off_compare_products` rows and `off_get_product`, printed beside the grade (`b (1)`). Nutri-Score points rank products of one kind only. In an `off_get_product` `fields` subset each brings its grade.
|
|
13
|
+
- **`quantity`, `completeness`** ([#92](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/92)): on every `off_search_products` row.
|
|
14
|
+
- **`last_modified`, `created`** ([#96](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/96)): ISO 8601 record times on `off_search_products` rows and `off_get_product`, and `fields` values there. A text-search row carries the indexed revision's.
|
|
15
|
+
- **`text_index_as_of`** ([#95](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/95)): the time of the newest record in the text index, on `off_search_products` answers the index served. `text_index_snapshot` names it; with no date it keeps its undated wording.
|
|
16
|
+
- **`mirror_fields_unread` on `off_compare_products` rows**: a row served from a mirror row that predates the score points names the fields it lacks. The comparison sends no live read for them; `off_get_product` reads them.
|
|
17
|
+
|
|
18
|
+
## Changed
|
|
19
|
+
|
|
20
|
+
- **Mirror record version 3**: a mirror-backed server fully reloads its store on its next refresh. Until the reload reaches a product, a full `off_get_product` read of it goes live for the fields the older row lacks, while `off_compare_products` stays on the mirror and names them in `mirror_fields_unread`. Stored products grow about 10% (mean 4,387 → 4,829 bytes in the fixture sample).
|
|
21
|
+
- **Text index date probe**: a text search beside its own request reads the index date, at most one probe per 6 hours (per 15 minutes while it keeps failing), drawing on the `OFF_RATE_LIMIT_SEARCH` budget only while two slots are free.
|
|
22
|
+
- **`brands_tag` on the mirror** ([#94](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/94)): a tag-only search is served from the mirror only for a brand it holds products under; any other brand reads live. For such a brand, `page` 11 or later sends one live count: matches that end before the page answer it empty with that total, and matches that reach into it fail as `page_out_of_range` naming the brand and the live total.
|
|
23
|
+
|
|
24
|
+
## Fixed
|
|
25
|
+
|
|
26
|
+
- **Total carbohydrates** ([#90](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/90)): a record holding only `carbohydrates-total` no longer reads as Carbohydrates `N/A`, and Sugars and Saturated fat no longer nest under a parent line the record lacks. `carbohydrates_total_100g` is its own `off_get_product` nutriment and `off_compare_products` column, never derived from `carbohydrates_100g`; on `off_get_product` the per-100 g figure moves there from `additional_100g.carbohydrates_total`.
|
|
27
|
+
- **`brands_tag`** ([#94](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/94)): a brand name is slugged as Open Food Facts slugs it (`Nestlé` → `nestle`, `Meßmer` → `messmer`), where an accent returned an exact zero; brand synonyms resolve only on a search reading the live database.
|
|
28
|
+
- **Mirror serving size**: a household measure with a mass in brackets (`1/2 cup (60 g)`) reads back in the mass's unit, as a live read does, and a spoon or glass alone parses as Product Opener's units table reads it (`1 tbsp` is 15 ml).
|
|
29
|
+
- **Record times**: `last_modified` and `created` are omitted for a time at or before the epoch, never reported as one.
|
|
30
|
+
- **`completeness`**: a numeric string Open Food Facts stored (`"0.65"`) is read as the number.
|
|
31
|
+
- **Singular totals**: a total of 1 reads "1 total product" and "1 matching product exists".
|
|
32
|
+
- **Empty-result line**: it no longer points every search at `off_browse_taxonomy`; a brand-only search is pointed at `query`, since the taxonomy holds no brands.
|
|
33
|
+
- **Page 11 or later refusal**: an unconfirmed value's recovery hint goes by why it went unconfirmed: a value no tag matches is to be corrected or dropped, and one whose lookup failed is to be retried.
|
|
34
|
+
- **Brands and taxonomy values ending in Σ**: a text search sends an unconfirmed one under both IDs as one OR group, so `categories_tag: "EL:ΧΥΜΌΣ"` with a nutrient filter finds the 2 products filed under `el:χυμός`. Such a value and its `σ`-typed twin no longer share one cached taxonomy lookup.
|
|
35
|
+
|
|
36
|
+
## Dependencies
|
|
37
|
+
|
|
38
|
+
- **`@biomejs/biome`** ^2.6.6 → ^2.6.8, **`better-sqlite3`** ^13.0.3 → ^13.2.0, **`ignore`** ^7.0.14 → ^7.0.16, **`vitest`** ^5.1.0 → ^5.1.1.
|
|
39
|
+
- The Bun test lane runs Vitest's threads pool (`vitest.config.ts`), since the fork pool needs a `channel.unref()` Bun lacks.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
---
|
|
2
|
+
summary: "off_search_products text searches work again on search-a-licious 2.x; brand spellings and Open Food Facts brand synonyms match on the mirror, live, and text paths; mirror freshness notes bound computed values and removals. outside_constraints is removed."
|
|
3
|
+
breaking: true
|
|
4
|
+
security: false
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# 0.5.0 — 2026-11-24
|
|
8
|
+
|
|
9
|
+
## Added
|
|
10
|
+
|
|
11
|
+
- **`bun run brands:sync`** ([#98](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/98)): regenerates the brand synonym table from openfoodfacts-server `taxonomies/brands.txt` at a recorded commit (195 groups holding 243 extra keys at `c6a9ede`). It writes nothing when two entries claim one key or a computed ID is missing from the published brands taxonomy.
|
|
12
|
+
|
|
13
|
+
## Changed
|
|
14
|
+
|
|
15
|
+
- **Mirror record version 4**: a mirror-backed server fully reloads its store on its next refresh. Until that reload completes, a tag-only search carrying `brands_tag` reads the live database (on the hosted server, about 2–5 hours after deploy: the next refresh within 3 hours, then the reload), and a page past 10 of such a search is answered from one live count: empty with the total when the matches end before it, refused as `page_out_of_range` when they reach into it.
|
|
16
|
+
- **`brands_tag`** ([#98](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/98)): every spelling of a brand and every other name its Open Food Facts brand entry lists (`7-Up`, `7up`, `Seven Up`) count the same products on the mirror, on a live tag search, and on a text search.
|
|
17
|
+
- **`query`** ([#101](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/101)): words are sent lowercased, escaped, and space-joined, and the 2.x index matches each against product and generic names only, now in each product's main language too (`langs` adds `main`); category, label, and brand wording belongs in the tag filters.
|
|
18
|
+
- **`nutrient_filters`** ([#101](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/101)): each bound is compared as given, decimals included, for all nine nutrients. A bound reaches only records whose indexed entry carries that nutrient (47 of 1,447 `en:skyrs` records), so a matching product can be missing; the parameter description and `text_index_snapshot` say so.
|
|
19
|
+
- **`additives_tag`** ([#101](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/101)): combines with `query`, `nutrient_filters`, and `ingredients_tag`; the `additives_filter_needs_tag_search` refusal is gone.
|
|
20
|
+
- **Upstream 400s** ([#101](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/101)): the message carries the 2.x error description, and the `upstream_rejected` hint no longer asks the caller to correct filter values.
|
|
21
|
+
- **`mirror_snapshot`** ([#99](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/99)): on `off_get_product`, `off_compare_products`, and `off_search_products` it says computed values are as of the record's last edit or the copy's last full reload (about every 30 days), and that a removed product can still be shown. The `not_found` outcome of the live read for fields a mirror row predates no longer bounds the removal by `mirror_as_of`.
|
|
22
|
+
|
|
23
|
+
## Removed
|
|
24
|
+
|
|
25
|
+
- **`outside_constraints`** ([#101](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/101)): removed from `off_search_products`. The text index compares nutrient bounds as given, decimals included, so no row it returns falls outside `nutrient_filters` and none is left off.
|
|
26
|
+
|
|
27
|
+
## Fixed
|
|
28
|
+
|
|
29
|
+
- **`off_search_products` text search** ([#101](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/101)): `query`, `nutrient_filters`, and `ingredients_tag` searches build against search-a-licious 2.x, where every one failed with HTTP 400 in 0.4.5. A text-search row's `brands` are the index's stored forms (a slug or the name as typed, `xx:` dropped), not display names.
|
|
30
|
+
- **Resumed full load** ([#98](https://github.com/cyanheads/openfoodfacts-mcp-server/issues/98)): a mirror full load resumed under a newer build records the lowest record version that built its rows, so the next refresh reloads it, and until then a filter that needs the newer version reads live.
|
|
31
|
+
- **Page past the end**: the `content[]` header of a page beyond the result set names the page size, as `structuredContent` does.
|
|
@@ -6,6 +6,15 @@ import { z } from '@cyanheads/mcp-ts-core';
|
|
|
6
6
|
import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
|
|
7
7
|
import { type StoredAsSoldRead } from '../../../services/openfoodfacts/openfoodfacts-service.js';
|
|
8
8
|
import { type RawProduct } from '../../../services/openfoodfacts/types.js';
|
|
9
|
+
/** The `nutriscore_score` output field's description, one for both product tools. */
|
|
10
|
+
export declare const NUTRISCORE_POINTS_DESCRIPTION = "Nutri-Score points behind nutriscore_grade, Open Food Facts' own ranking: lower is better, and the grade is read off them. They rank products of one kind only: beverages, and fats, oils, nuts, and seeds, are graded on their own thresholds, so the same points can carry different grades across kinds. Absent when Open Food Facts computed none (never derived from the grade), or when mirror_fields_unread names it as not read.";
|
|
11
|
+
/** The `ecoscore_score` output field's description, one for both product tools. */
|
|
12
|
+
export declare const GREEN_SCORE_POINTS_DESCRIPTION = "Green-Score points behind ecoscore_grade: the world score, higher meaning lower environmental impact (\"a\" from 75, \"a-plus\" from 90), and bonuses can take it past 100. Absent when Open Food Facts computed none (never derived from the grade), or when mirror_fields_unread names it as not read.";
|
|
13
|
+
/**
|
|
14
|
+
* A grade as the text shows it, with the points behind it when the read carried them: `b (1)`.
|
|
15
|
+
* Points that came without a grade sit beside `N/A`, so neither surface drops them.
|
|
16
|
+
*/
|
|
17
|
+
export declare function gradeWithPoints(grade: string | undefined, points: number | undefined): string;
|
|
9
18
|
/** The failure reasons this tool declares — the four the service raises for a product fetch. */
|
|
10
19
|
declare const FAILURE_REASONS: readonly ['upstream_error', 'upstream_timeout', 'upstream_rejected', 'rate_limited'];
|
|
11
20
|
type FailureReason = (typeof FAILURE_REASONS)[number];
|
|
@@ -55,10 +64,13 @@ export declare const offCompareProductsTool: import("@cyanheads/mcp-ts-core").To
|
|
|
55
64
|
brands: z.ZodOptional<z.ZodString>;
|
|
56
65
|
found: z.ZodBoolean;
|
|
57
66
|
nutriscore_grade: z.ZodOptional<z.ZodString>;
|
|
67
|
+
nutriscore_score: z.ZodOptional<z.ZodNumber>;
|
|
58
68
|
nova_group: z.ZodOptional<z.ZodNumber>;
|
|
59
69
|
ecoscore_grade: z.ZodOptional<z.ZodString>;
|
|
70
|
+
ecoscore_score: z.ZodOptional<z.ZodNumber>;
|
|
60
71
|
prepared: z.ZodOptional<z.ZodObject<{
|
|
61
72
|
carbohydrates_100g: z.ZodOptional<z.ZodNumber>;
|
|
73
|
+
carbohydrates_total_100g: z.ZodOptional<z.ZodNumber>;
|
|
62
74
|
energy_kcal_100g: z.ZodOptional<z.ZodNumber>;
|
|
63
75
|
fat_100g: z.ZodOptional<z.ZodNumber>;
|
|
64
76
|
fiber_100g: z.ZodOptional<z.ZodNumber>;
|
|
@@ -83,7 +95,9 @@ export declare const offCompareProductsTool: import("@cyanheads/mcp-ts-core").To
|
|
|
83
95
|
off_mirror: "off_mirror";
|
|
84
96
|
}>>;
|
|
85
97
|
mirror_as_of: z.ZodOptional<z.ZodString>;
|
|
98
|
+
mirror_fields_unread: z.ZodOptional<z.ZodString>;
|
|
86
99
|
carbohydrates_100g: z.ZodOptional<z.ZodNumber>;
|
|
100
|
+
carbohydrates_total_100g: z.ZodOptional<z.ZodNumber>;
|
|
87
101
|
energy_kcal_100g: z.ZodOptional<z.ZodNumber>;
|
|
88
102
|
fat_100g: z.ZodOptional<z.ZodNumber>;
|
|
89
103
|
fiber_100g: z.ZodOptional<z.ZodNumber>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compare-products.tool.d.ts","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/compare-products.tool.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAQ,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAY,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"compare-products.tool.d.ts","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/compare-products.tool.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAQ,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAY,MAAM,+BAA+B,CAAC;AAa3E,OAAO,EAIL,KAAK,gBAAgB,EACtB,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAIL,KAAK,UAAU,EAChB,MAAM,mCAAmC,CAAC;AAU3C,qFAAqF;AACrF,eAAO,MAAM,6BAA6B,6aACkY,CAAC;AAE7a,mFAAmF;AACnF,eAAO,MAAM,8BAA8B,6SAC6P,CAAC;AAEzS;;;GAGG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAG7F;AAuID,gGAAgG;AAChG,QAAA,MAAM,eAAe,YACnB,gBAAgB,EAChB,kBAAkB,EAClB,mBAAmB,EACnB,cAAc,CACN,CAAC;AAEX,KAAK,aAAa,GAAG,CAAC,OAAO,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC;AAqCtD;;;GAGG;AACH,MAAM,MAAM,YAAY,GACpB;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,GAClB;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,GAClB;IAAE,MAAM,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,aAAa,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAkBpF;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,UAAU,EACnB,IAAI,EAAE,gBAAgB,GACrB;IAAE,OAAO,EAAE,UAAU,CAAC;IAAC,cAAc,EAAE,YAAY,CAAA;CAAE,CAgBvD;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM;;;;;;;;;+BAkDjD;AAmID,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA0bjC,CAAC"}
|
|
@@ -4,13 +4,29 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { tool, z } from '@cyanheads/mcp-ts-core';
|
|
6
6
|
import { JsonRpcErrorCode, McpError } from '@cyanheads/mcp-ts-core/errors';
|
|
7
|
-
import { mirrorCopyNote, mirrorSnapshotTrailer, sourcesLine, } from '../read-source.js';
|
|
7
|
+
import { mirrorCopyNote, mirrorSnapshotTrailer, sourcesLine, unreadFieldsNote, } from '../read-source.js';
|
|
8
|
+
import { completenessScore } from '../record-metadata.js';
|
|
8
9
|
import { applyAsSoldSelection, holdsOnlyPreparedFigures, } from '../../../services/openfoodfacts/nutrition-sets.js';
|
|
9
10
|
import { getOpenFoodFactsService, } from '../../../services/openfoodfacts/openfoodfacts-service.js';
|
|
10
11
|
import { BARCODE_PATTERN, BARCODE_PATTERN_MESSAGE, } from '../../../services/openfoodfacts/types.js';
|
|
11
12
|
import { mdInline } from '../../../utils/markdown.js';
|
|
12
|
-
/**
|
|
13
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Fields needed for comparison — narrower than full product fetch. Every one is a field the local
|
|
15
|
+
* copy holds, so a comparison is served from it for each barcode it holds.
|
|
16
|
+
*/
|
|
17
|
+
const COMPARE_FIELDS = 'product_name,brands,nutriscore_grade,nutriscore_score,nova_group,ecoscore_grade,ecoscore_score,nutriments,completeness';
|
|
18
|
+
/** The `nutriscore_score` output field's description, one for both product tools. */
|
|
19
|
+
export const NUTRISCORE_POINTS_DESCRIPTION = "Nutri-Score points behind nutriscore_grade, Open Food Facts' own ranking: lower is better, and the grade is read off them. They rank products of one kind only: beverages, and fats, oils, nuts, and seeds, are graded on their own thresholds, so the same points can carry different grades across kinds. Absent when Open Food Facts computed none (never derived from the grade), or when mirror_fields_unread names it as not read.";
|
|
20
|
+
/** The `ecoscore_score` output field's description, one for both product tools. */
|
|
21
|
+
export const GREEN_SCORE_POINTS_DESCRIPTION = 'Green-Score points behind ecoscore_grade: the world score, higher meaning lower environmental impact ("a" from 75, "a-plus" from 90), and bonuses can take it past 100. Absent when Open Food Facts computed none (never derived from the grade), or when mirror_fields_unread names it as not read.';
|
|
22
|
+
/**
|
|
23
|
+
* A grade as the text shows it, with the points behind it when the read carried them: `b (1)`.
|
|
24
|
+
* Points that came without a grade sit beside `N/A`, so neither surface drops them.
|
|
25
|
+
*/
|
|
26
|
+
export function gradeWithPoints(grade, points) {
|
|
27
|
+
const shown = grade === undefined ? 'N/A' : mdInline(grade);
|
|
28
|
+
return points === undefined ? shown : `${shown} (${points})`;
|
|
29
|
+
}
|
|
14
30
|
/**
|
|
15
31
|
* Most distinct barcodes one call fetches. More, up to the input's hard ceiling, are listed in
|
|
16
32
|
* `unprocessed` without being fetched, so one compare never spends more of the per-minute product
|
|
@@ -46,7 +62,13 @@ const NUTRITION_COLUMNS = [
|
|
|
46
62
|
key: 'carbohydrates_100g',
|
|
47
63
|
raw: 'carbohydrates',
|
|
48
64
|
header: 'Carbohydrates (g)',
|
|
49
|
-
measure: '
|
|
65
|
+
measure: "Carbohydrates in grams (Open Food Facts' carbohydrates nutrient, which records entered from US labels often fill with the label's total, fiber included; carbohydrates_total_100g is the separate total including fiber)",
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
key: 'carbohydrates_total_100g',
|
|
69
|
+
raw: 'carbohydrates-total',
|
|
70
|
+
header: 'Total Carbs incl. Fiber (g)',
|
|
71
|
+
measure: 'Total carbohydrates including fiber, a separate Open Food Facts nutrient from carbohydrates_100g and never derived from it, in grams',
|
|
50
72
|
},
|
|
51
73
|
{ key: 'sugars_100g', raw: 'sugars', header: 'Sugars (g)', measure: 'Total sugars in grams' },
|
|
52
74
|
{ key: 'salt_100g', raw: 'salt', header: 'Salt (g)', measure: 'Salt in grams' },
|
|
@@ -268,8 +290,8 @@ function sourceGroups(rows) {
|
|
|
268
290
|
return groups;
|
|
269
291
|
}
|
|
270
292
|
/**
|
|
271
|
-
* Build a comparison row from a raw product,
|
|
272
|
-
* as-sold read went when one ran.
|
|
293
|
+
* Build a comparison row from a raw product, the read it came from (its source, and the fields a
|
|
294
|
+
* mirror row predates and so lacks), and how its stored as-sold read went when one ran.
|
|
273
295
|
*/
|
|
274
296
|
function buildCompareRow(barcode, raw, from, storedAsSold) {
|
|
275
297
|
const row = { barcode, found: true };
|
|
@@ -279,12 +301,18 @@ function buildCompareRow(barcode, raw, from, storedAsSold) {
|
|
|
279
301
|
row.brands = raw.brands;
|
|
280
302
|
if (raw.nutriscore_grade)
|
|
281
303
|
row.nutriscore_grade = raw.nutriscore_grade;
|
|
304
|
+
// Points are passed through as Open Food Facts computed them, never derived from a grade.
|
|
305
|
+
if (typeof raw.nutriscore_score === 'number')
|
|
306
|
+
row.nutriscore_score = raw.nutriscore_score;
|
|
282
307
|
if (typeof raw.nova_group === 'number')
|
|
283
308
|
row.nova_group = raw.nova_group;
|
|
284
309
|
if (raw.ecoscore_grade)
|
|
285
310
|
row.ecoscore_grade = raw.ecoscore_grade;
|
|
286
|
-
if (typeof raw.
|
|
287
|
-
row.
|
|
311
|
+
if (typeof raw.ecoscore_score === 'number')
|
|
312
|
+
row.ecoscore_score = raw.ecoscore_score;
|
|
313
|
+
const completeness = completenessScore(raw.completeness);
|
|
314
|
+
if (completeness !== undefined)
|
|
315
|
+
row.completeness = completeness;
|
|
288
316
|
if (raw.nutriments) {
|
|
289
317
|
Object.assign(row, readFigures(raw.nutriments, '_100g'));
|
|
290
318
|
const prepared = readFigures(raw.nutriments, '_prepared_100g');
|
|
@@ -294,13 +322,16 @@ function buildCompareRow(barcode, raw, from, storedAsSold) {
|
|
|
294
322
|
if (storedAsSold)
|
|
295
323
|
row.stored_as_sold = storedAsSold;
|
|
296
324
|
row.source = from.source;
|
|
297
|
-
if (from.source === 'off_mirror')
|
|
325
|
+
if (from.source === 'off_mirror') {
|
|
298
326
|
row.mirror_as_of = from.mirrorAsOf;
|
|
327
|
+
if (from.unread)
|
|
328
|
+
row.mirror_fields_unread = unreadFieldsNote(from.unread, from.mirrorAsOf);
|
|
329
|
+
}
|
|
299
330
|
return row;
|
|
300
331
|
}
|
|
301
332
|
export const offCompareProductsTool = tool('off_compare_products', {
|
|
302
333
|
title: 'Compare Food Products Side-by-Side',
|
|
303
|
-
description: 'Side-by-side nutrition and scoring comparison for 2–10 products per call by barcode; a repeated barcode is compared once, so two identical barcodes yield one row, and barcodes past the 10th distinct one are listed in unprocessed rather than fetched. Returns a normalized table of energy (kcal), fat, saturated fat, carbohydrates, sugars, salt, protein, and fiber per 100 g, or per 100 ml for liquids, plus Nutri-Score,
|
|
334
|
+
description: 'Side-by-side nutrition and scoring comparison for 2–10 products per call by barcode; a repeated barcode is compared once, so two identical barcodes yield one row, and barcodes past the 10th distinct one are listed in unprocessed rather than fetched. Returns a normalized table of energy (kcal), fat, saturated fat, carbohydrates, total carbohydrates including fiber, sugars, salt, protein, and fiber per 100 g, or per 100 ml for liquids, plus Nutri-Score and Green-Score, each with the points behind its grade, and NOVA group. Open Food Facts returns one preparation state per read, so figures for the prepared product arrive in a prepared object on the row, with the same columns and basis, and never fill an as-sold field; a row whose read returned only prepared figures gets one more product read, of the as-sold set its record stores, once the read of every barcode has settled, with stored_as_sold saying how it went. Designed for "which of these cereals is healthiest?" or "compare these pasta brands" workflows. Missing nutrition data for any product is preserved as absent — comparisons are not imputed. A batch is not all-or-nothing: barcodes that resolve are returned even when others fail, with confirmed-missing barcodes listed in not_found and failed fetches listed separately in failed. Scores carry regional formula caveats; Nutri-Score points break a grade tie only between products of one kind. Data under ODbL 1.0 — cite Open Food Facts in downstream use.',
|
|
304
335
|
annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
|
|
305
336
|
input: z.object({
|
|
306
337
|
barcodes: z
|
|
@@ -330,6 +361,7 @@ export const offCompareProductsTool = tool('off_compare_products', {
|
|
|
330
361
|
.string()
|
|
331
362
|
.optional()
|
|
332
363
|
.describe('Nutri-Score grade: "a" through "e", "unknown" when the nutrition data entered is not enough to compute it, or "not-applicable" for product categories the score does not cover. Absent when Open Food Facts sent none.'),
|
|
364
|
+
nutriscore_score: z.number().optional().describe(NUTRISCORE_POINTS_DESCRIPTION),
|
|
333
365
|
nova_group: z
|
|
334
366
|
.number()
|
|
335
367
|
.optional()
|
|
@@ -338,6 +370,7 @@ export const offCompareProductsTool = tool('off_compare_products', {
|
|
|
338
370
|
.string()
|
|
339
371
|
.optional()
|
|
340
372
|
.describe('Green-Score (formerly Eco-Score) environmental impact grade: "a-plus" (lowest impact), then "a" through "f"; "unknown" when the data it needs is missing, or "not-applicable" for product categories the score does not cover. Often absent.'),
|
|
373
|
+
ecoscore_score: z.number().optional().describe(GREEN_SCORE_POINTS_DESCRIPTION),
|
|
341
374
|
...nutritionFields((measure) => `${measure} per 100 g, or per 100 ml for liquids, as sold. When the product read returned only prepared figures, read from the record's stored as-sold set instead (see stored_as_sold). Absent when not entered, or when that stored set was not read.`),
|
|
342
375
|
prepared: z
|
|
343
376
|
.object(nutritionFields((measure) => `${measure} per 100 g, or per 100 ml for liquids, as prepared. Absent when this read returned no such figure.`))
|
|
@@ -347,7 +380,7 @@ export const offCompareProductsTool = tool('off_compare_products', {
|
|
|
347
380
|
completeness: z
|
|
348
381
|
.number()
|
|
349
382
|
.optional()
|
|
350
|
-
.describe('Data completeness
|
|
383
|
+
.describe('Data completeness score as Open Food Facts reports it: higher means more of the record is filled in, and it can exceed 1 (e.g. 1.0875). Low values mean many fields are missing.'),
|
|
351
384
|
source: z
|
|
352
385
|
.enum(['off_api', 'off_mirror'])
|
|
353
386
|
.optional()
|
|
@@ -356,6 +389,10 @@ export const offCompareProductsTool = tool('off_compare_products', {
|
|
|
356
389
|
.string()
|
|
357
390
|
.optional()
|
|
358
391
|
.describe('ISO 8601 time up to which the local copy reflects every product contributed or edited on Open Food Facts. Present only when source is "off_mirror".'),
|
|
392
|
+
mirror_fields_unread: z
|
|
393
|
+
.string()
|
|
394
|
+
.optional()
|
|
395
|
+
.describe('Present only when source is "off_mirror" and the local copy holds this product from before it stored fields a comparison reads, such as nutriscore_score and ecoscore_score. Names the fields this row lacks for that reason, which are not read rather than not entered: a comparison sends no live read for them, and off_get_product reads them for the barcode.'),
|
|
359
396
|
})
|
|
360
397
|
.describe('A single product comparison row.'))
|
|
361
398
|
.describe('Comparison rows in input order — one per distinct barcode whose fetch completed, whether or not a record exists. Barcodes whose fetch failed have no row here; they appear in failed. Barcodes past the cap appear in unprocessed.'),
|
|
@@ -389,7 +426,7 @@ export const offCompareProductsTool = tool('off_compare_products', {
|
|
|
389
426
|
mirror_snapshot: z
|
|
390
427
|
.string()
|
|
391
428
|
.optional()
|
|
392
|
-
.describe(
|
|
429
|
+
.describe("Present only when a row's source is \"off_mirror\". States that those rows come from the local copy, which reflects contributor edits through their mirror_as_of, so a later one is not; that computed values (grades, nutrient levels, estimated nutrients, parsed ingredients and their analysis, additives, allergens and traces, completeness, data-quality tags) are as of the record's last edit or the copy's last full reload (about every 30 days), whichever is later; and that a product removed since that reload can still be shown."),
|
|
393
430
|
},
|
|
394
431
|
enrichmentTrailer: {
|
|
395
432
|
mirror_snapshot: { render: mirrorSnapshotTrailer },
|
|
@@ -435,7 +472,10 @@ export const offCompareProductsTool = tool('off_compare_products', {
|
|
|
435
472
|
const distinct = [...new Set(input.barcodes)];
|
|
436
473
|
const compared = distinct.slice(0, COMPARE_BARCODE_CAP);
|
|
437
474
|
const unprocessed = distinct.slice(COMPARE_BARCODE_CAP);
|
|
438
|
-
|
|
475
|
+
// A row the local copy holds from before it stored a compared field is served as it is, the
|
|
476
|
+
// field named unread, rather than read live: a reload rewrites rows over hours, and reading each
|
|
477
|
+
// such barcode live would spend the product budget the copy exists to spare.
|
|
478
|
+
const settlements = await Promise.allSettled(compared.map((barcode) => svc.getProductFields(barcode, COMPARE_FIELDS, ctx, 'serve_row')));
|
|
439
479
|
/*
|
|
440
480
|
* A row whose read returned only prepared figures gets one read of its record's stored sets.
|
|
441
481
|
* These start once every v2 read has settled: a v2 read's retry spends its budget slot late, and
|
|
@@ -483,7 +523,7 @@ export const offCompareProductsTool = tool('off_compare_products', {
|
|
|
483
523
|
const [mirrorAsOf, ...otherTimes] = new Set(products.flatMap((row) => row.mirror_as_of ?? []));
|
|
484
524
|
if (mirrorAsOf !== undefined) {
|
|
485
525
|
ctx.enrich({
|
|
486
|
-
mirror_snapshot: mirrorCopyNote('The rows whose source is off_mirror come', otherTimes.length === 0 ? mirrorAsOf : 'the mirror_as_of each
|
|
526
|
+
mirror_snapshot: mirrorCopyNote('The rows whose source is off_mirror come', otherTimes.length === 0 ? mirrorAsOf : 'the mirror_as_of each row carries', 'a later one is not'),
|
|
487
527
|
});
|
|
488
528
|
}
|
|
489
529
|
ctx.log.info('Product comparison completed', {
|
|
@@ -537,8 +577,7 @@ export const offCompareProductsTool = tool('off_compare_products', {
|
|
|
537
577
|
const completeness = p.completeness !== undefined
|
|
538
578
|
? `${Math.round(p.completeness * 100)}% (${p.completeness})`
|
|
539
579
|
: 'N/A';
|
|
540
|
-
|
|
541
|
-
lines.push(`| ${name} | ${p.barcode} | ${p.found} | ${grade(p.nutriscore_grade)} | ${p.nova_group ?? 'N/A'} | ${grade(p.ecoscore_grade)} | ${completeness} |`);
|
|
580
|
+
lines.push(`| ${name} | ${p.barcode} | ${p.found} | ${gradeWithPoints(p.nutriscore_grade, p.nutriscore_score)} | ${p.nova_group ?? 'N/A'} | ${gradeWithPoints(p.ecoscore_grade, p.ecoscore_score)} | ${completeness} |`);
|
|
542
581
|
}
|
|
543
582
|
// Nutrition tables. Each block stands alone, since a batch can fall entirely to one side. A row
|
|
544
583
|
// with prepared figures and no as-sold one leaves the as-sold table: its N/As would sit under a
|
|
@@ -583,9 +622,14 @@ export const offCompareProductsTool = tool('off_compare_products', {
|
|
|
583
622
|
// Scoped rather than dropped when an "as prepared" table prints: Scores keeps its N/As even
|
|
584
623
|
// when no as-sold table does.
|
|
585
624
|
const naScope = asPrepared.length > 0 ? ' outside the "as prepared" table' : '';
|
|
586
|
-
// The rows' sources, one line for the whole comparison, close the answer above its footer
|
|
625
|
+
// The rows' sources, one line for the whole comparison, close the answer above its footer,
|
|
626
|
+
// with the fields rows the local copy predates lack. Those are missing because they were not
|
|
627
|
+
// read, so the footer's claim narrows to exclude them.
|
|
587
628
|
const [firstSource, ...otherSources] = sourceGroups(result.products);
|
|
588
|
-
|
|
629
|
+
const unread = found.flatMap((p) => p.mirror_fields_unread === undefined
|
|
630
|
+
? []
|
|
631
|
+
: [`- ${p.barcode}: ${mdInline(p.mirror_fields_unread)}`]);
|
|
632
|
+
lines.push('', ...(firstSource ? [sourcesLine([firstSource, ...otherSources])] : []), ...(unread.length > 0 ? ['**Unread fields:**', ...unread] : []), `*Data: Open Food Facts (ODbL 1.0) — crowd-sourced. "N/A"${naScope} = not yet entered${unread.length > 0 ? '; unread fields = not read' : ''}.*`);
|
|
589
633
|
return [{ type: 'text', text: lines.join('\n') }];
|
|
590
634
|
},
|
|
591
635
|
});
|