Repository avatar
Search & Data Extraction
v0.5.0
active

openfoodfacts-mcp-server

io.github.cyanheads/openfoodfacts-mcp-server

Barcode lookup, nutrition search, and product comparison for 3M+ crowd-sourced food products.

Documentation

@cyanheads/openfoodfacts-mcp-server

Look up food products by barcode, search by keyword, tag, allergen, or nutrition filter, compare products side-by-side, and browse the canonical tag vocabulary via MCP. STDIO or Streamable HTTP.

4 Tools

Version License Docker MCP SDK npm TypeScript Bun

Install in Claude Desktop Install in Cursor Install in VS Code

Framework


Overview

Packaged-food data from Open Food Facts, a crowd-sourced database of 3M+ products. Look up items by barcode, search by text, tags, allergens, and nutrient thresholds, compare products side by side, and resolve everyday terms to the canonical tags the filters take.

Tools

ToolDescription
off_get_productFetch one product by barcode: ingredients, allergens and traces, additives, scores, nutrition, and tags
off_search_productsSearch by text, tag filters, allergen exclusions, and nutrient thresholds (per 100 g, or per 100 ml for liquids); returns summary rows with barcodes
off_compare_productsCompare up to 10 products per call by barcode on nutrition (per 100 g, or per 100 ml for liquids), Nutri-Score, NOVA, and Green-Score
off_browse_taxonomyResolve a human term to the canonical tag ID that off_search_products filters on

Skills

SkillDescription
openfoodfacts-guideJudgment for calling the tools: allergy checks that never overclaim, choosing among a product's barcodes, where tag IDs come from, grade ranges, free-from searches, and the shared search budget. Served over MCP as skill://openfoodfacts-guide/SKILL.md and shipped in the plugin, npm package, and .mcpb bundle.

Capability reference

off_get_product tool

  • 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
  • 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
  • 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
  • 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
  • source (off_api or off_mirror) names where the product was read; a barcode a local 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

off_search_products tool

  • 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
  • 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
  • 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)
  • 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
  • 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
  • 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 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
  • 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

off_compare_products tool

  • 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
  • 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
  • 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
  • Each row carries source (off_api or off_mirror), and mirror_as_of for a row read from a local 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
  • 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

off_browse_taxonomy tool

  • facet is one of categories, labels, allergens, additives, countries, ingredients, nova_groups, nutrition_grades; search matches a substring of the tag ID, name, or a synonym ("shellfish" → en:crustaceans), and the tag the term itself names (US → en:united-states) is listed first; limit (default 20) returns up to 200 per call, with no input maximum (a larger value returns the first 200); a cut result says how many matched; no paging. Each lookup asks for up to 2,000 suggestions, above the largest answer measured (1,313), so an E-number term such as e314 resolves to en:e314 and the match count is exact below that size
  • Returns tags[] of id and name, where id goes to off_search_products unchanged; nova_groups and nutrition_grades come back complete with total_in_facet
  • The six open facets resolve against the live Open Food Facts taxonomy. Five fall back to a small offline sample, with a notice, when it is unavailable, and omitting search returns only that sample. ingredients has no sample: it lists nothing without a search or when the lookup fails, and its IDs are singular (oat resolves to en:oat, oats to nothing)

Features

Built on @cyanheads/mcp-ts-core: stdio and Streamable HTTP transports, pluggable auth (none / jwt / oauth), swappable storage (in-memory, filesystem, Supabase, Cloudflare KV/R2/D1), structured logging with optional OpenTelemetry tracing.

Open Food Facts-specific:

  • No API key; the identifying User-Agent Open Food Facts' terms require is built in
  • 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
  • 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
  • Optional 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
  • Nutriments normalized from hyphenated keys (energy-kcal_100g → energy_kcal_100g), with additional_100g / additional_serving maps that label each nutrient with its unit
  • 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
  • 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

Agent-friendly output:

  • Per-serving nutrition carries its denominator: serving_size, serving_quantity, serving_quantity_unit, and a note when none is recorded
  • Graceful partial failure: off_compare_products returns resolved rows alongside not_found and failed
  • Explicit count bounds: total_is_lower_bound, last_page, and omitted on searches
  • 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

Getting started

Connect to the hosted instance, no install:

claude mcp add --transport http openfoodfacts-mcp-server https://openfoodfacts.caseyjhand.com/mcp

Or run it locally:

claude mcp add openfoodfacts-mcp-server -- npx -y @cyanheads/openfoodfacts-mcp-server

For other clients, add this to the MCP config file:

{
  "mcpServers": {
    "openfoodfacts-mcp-server": {
      "command": "npx",
      "args": ["-y", "@cyanheads/openfoodfacts-mcp-server"]
    }
  }
}

No API key or account is needed: the server identifies itself to Open Food Facts with its own User-Agent. For Docker or a source build, see Running the server.

Configuration

VariableDescriptionDefault
OFF_BASE_URLOpen Food Facts API base URL.https://world.openfoodfacts.org
OFF_RATE_LIMIT_PRODUCTProduct read budget (requests/min). The default is Open Food Facts' published per-IP limit; lower it on a shared outbound IP.15
OFF_RATE_LIMIT_SEARCHSearch 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
OFF_RATE_LIMIT_TAXONOMYTaxonomy lookup budget (requests/min), shared by off_browse_taxonomy, tag canonicalization on text searches, and exclusion checks.10
OFF_MIRROR_PATHPath of the local export mirror's SQLite file. Unset disables the mirror. Works from a source checkout or the Docker image only.unset
MCP_TRANSPORT_TYPETransport: stdio or http.stdio
MCP_HTTP_PORTHTTP server port.3010
MCP_AUTH_MODEAuth mode: none, jwt, or oauth.none
MCP_LOG_LEVELLog level (debug, info, warning, error).info
LOG_TOOL_FAILURE_PAYLOADSLog each failed tool call's arguments and result, redacted by key name and capped at LOG_TOOL_FAILURE_PAYLOAD_MAX_BYTES (default 16384). A secret inside a free-form value is not redacted.false
OTEL_ENABLEDEnable OpenTelemetry instrumentation.false

See .env.example for the full list of optional overrides.

Running the server

Local development

Requires Bun v1.4.4 or higher (or Node.js v24+).

  • Clone and install:

    git clone https://github.com/cyanheads/openfoodfacts-mcp-server.git
    cd openfoodfacts-mcp-server && bun install
    cp .env.example .env   # optional: override rate limits or the base URL
    
  • Build and run:

    # One-time build
    bun run rebuild
    
    # Run the built server
    bun run start:stdio
    # or
    bun run start:http
    
  • Run checks and tests:

    bun run devcheck   # Lint, format, typecheck, security
    bun run test       # Vitest test suite
    bun run lint:mcp   # Validate MCP definitions against spec
    

Docker

docker run --rm -p 3010:3010 ghcr.io/cyanheads/openfoodfacts-mcp-server:latest

The image defaults to HTTP transport, stateless session mode, and logs to /var/log/openfoodfacts-mcp-server. To run it over stdio from an MCP client, use "command": "docker" with "args": ["run", "-i", "--rm", "-e", "MCP_TRANSPORT_TYPE=stdio", "ghcr.io/cyanheads/openfoodfacts-mcp-server:latest"]. To build locally, docker build -t openfoodfacts-mcp-server .; OpenTelemetry peer dependencies are installed by default — build with --build-arg OTEL_ENABLED=false to omit them.

Local export mirror

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.

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:

docker run -d --name openfoodfacts-mcp-server -p 3010:3010 \
  -v off-mirror:/usr/src/app/.mirror \
  -e OFF_MIRROR_PATH=/usr/src/app/.mirror/openfoodfacts.sqlite \
  ghcr.io/cyanheads/openfoodfacts-mcp-server:latest

docker exec openfoodfacts-mcp-server bun run mirror:init     # full load of the export, then the deltas since; re-run after an interrupt to resume
docker exec openfoodfacts-mcp-server bun run mirror:status   # health, product count, and the as-of time answers cite
docker exec openfoodfacts-mcp-server bun run mirror:verify   # status plus SQLite's integrity check
docker exec openfoodfacts-mcp-server bun run mirror:refresh  # one delta pass by hand

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.

Project structure

DirectoryPurpose
src/index.tscreateApp() entry point — registers tools and the published skills, and inits services.
src/configServer-specific environment variable parsing and validation with Zod.
src/mcp-server/toolsTool definitions (*.tool.ts).
src/services/openfoodfactsOpen Food Facts API client — HTTP, rate limiting, retry, field normalization.
src/services/mirrorLocal export mirror — SQLite store, record builder, export and delta ingester, tag-search queries, and the refresh schedule.
scripts/mirror-*.tsmirror:init, mirror:refresh, mirror:status, and mirror:verify.
scripts/brands-sync.tsbrands:sync, which regenerates the brand synonym table from Open Food Facts' brands taxonomy.
src/services/taxonomyTag vocabulary — live resolution, offline sample, tag-value canonicalization, and brand keys.
src/utilsMarkdown escaping for contributor-entered values in text output.
skills/Published Agent Skills for the agents that call the tools.
tests/Unit and integration tests mirroring src/.

Development guide

See CLAUDE.md for development guidelines and architectural rules. The short version:

  • Handlers throw, framework catches — no try/catch in tool logic
  • Use ctx.log for request-scoped logging, ctx.state for tenant-scoped storage
  • Register new tools via the barrel in src/mcp-server/tools/definitions/index.ts
  • Wrap external API calls: validate raw → normalize to domain type → return output schema; never fabricate missing fields

Contributing

Issues are welcome — see CONTRIBUTING.md for the forms and what makes a report actionable. Report vulnerabilities through private disclosure, never a public issue. Run checks and tests before submitting:

bun run devcheck
bun run test

License

Apache-2.0 — see LICENSE for details. Open Food Facts data is released under the Open Database License (ODbL) 1.0; downstream use must cite Open Food Facts.

NPM
@cyanheads/openfoodfacts-mcp-server
Install Command
npm install @cyanheads/openfoodfacts-mcp-server
Runtime: npx
NPM
@cyanheads/openfoodfacts-mcp-server
Install Command
npm install @cyanheads/openfoodfacts-mcp-server
Runtime: npx