@cyanheads/openfoodfacts-mcp-server 0.3.2 → 0.3.4

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 (46) hide show
  1. package/AGENTS.md +47 -20
  2. package/CLAUDE.md +47 -20
  3. package/README.md +45 -58
  4. package/changelog/0.3.x/0.3.3.md +30 -0
  5. package/changelog/0.3.x/0.3.4.md +19 -0
  6. package/changelog/template.md +7 -24
  7. package/dist/config/server-config.d.ts +6 -0
  8. package/dist/config/server-config.d.ts.map +1 -1
  9. package/dist/config/server-config.js +6 -0
  10. package/dist/config/server-config.js.map +1 -1
  11. package/dist/index.js +2 -6
  12. package/dist/index.js.map +1 -1
  13. package/dist/mcp-server/tools/definitions/browse-taxonomy.tool.d.ts.map +1 -1
  14. package/dist/mcp-server/tools/definitions/browse-taxonomy.tool.js +6 -3
  15. package/dist/mcp-server/tools/definitions/browse-taxonomy.tool.js.map +1 -1
  16. package/dist/mcp-server/tools/definitions/compare-products.tool.d.ts.map +1 -1
  17. package/dist/mcp-server/tools/definitions/compare-products.tool.js +40 -6
  18. package/dist/mcp-server/tools/definitions/compare-products.tool.js.map +1 -1
  19. package/dist/mcp-server/tools/definitions/get-product.tool.d.ts +6 -0
  20. package/dist/mcp-server/tools/definitions/get-product.tool.d.ts.map +1 -1
  21. package/dist/mcp-server/tools/definitions/get-product.tool.js +116 -30
  22. package/dist/mcp-server/tools/definitions/get-product.tool.js.map +1 -1
  23. package/dist/mcp-server/tools/definitions/index.d.ts +32 -4
  24. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -1
  25. package/dist/mcp-server/tools/definitions/search-products.tool.d.ts +28 -5
  26. package/dist/mcp-server/tools/definitions/search-products.tool.d.ts.map +1 -1
  27. package/dist/mcp-server/tools/definitions/search-products.tool.js +134 -36
  28. package/dist/mcp-server/tools/definitions/search-products.tool.js.map +1 -1
  29. package/dist/services/openfoodfacts/openfoodfacts-service.d.ts +14 -1
  30. package/dist/services/openfoodfacts/openfoodfacts-service.d.ts.map +1 -1
  31. package/dist/services/openfoodfacts/openfoodfacts-service.js +138 -26
  32. package/dist/services/openfoodfacts/openfoodfacts-service.js.map +1 -1
  33. package/dist/services/openfoodfacts/types.d.ts +44 -6
  34. package/dist/services/openfoodfacts/types.d.ts.map +1 -1
  35. package/dist/services/openfoodfacts/types.js +22 -3
  36. package/dist/services/openfoodfacts/types.js.map +1 -1
  37. package/dist/services/taxonomy/taxonomy-service.d.ts +1 -1
  38. package/dist/services/taxonomy/taxonomy-service.d.ts.map +1 -1
  39. package/dist/services/taxonomy/taxonomy-service.js +68 -62
  40. package/dist/services/taxonomy/taxonomy-service.js.map +1 -1
  41. package/dist/utils/markdown.d.ts +42 -0
  42. package/dist/utils/markdown.d.ts.map +1 -0
  43. package/dist/utils/markdown.js +67 -0
  44. package/dist/utils/markdown.js.map +1 -0
  45. package/package.json +8 -7
  46. package/server.json +3 -3
package/AGENTS.md CHANGED
@@ -1,11 +1,11 @@
1
1
  # Developer Protocol
2
2
 
3
3
  **Server:** openfoodfacts-mcp-server
4
- **Version:** 0.3.2
5
- **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.12.3`
6
- **Engines:** Bun ≥1.3.0, Node ≥24.0.0
4
+ **Version:** 0.3.4
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.13.3`
6
+ **Engines:** Bun ≥1.4.0, Node ≥24.0.0
7
7
  **MCP SDK:** `@modelcontextprotocol/server` ^2.0.0
8
- **Zod:** ^4.4.3
8
+ **Zod:** ^4.6.5
9
9
 
10
10
  > **Read the framework docs first:** `node_modules/@cyanheads/mcp-ts-core/CLAUDE.md` contains the full API reference — builders, Context, error codes, exports, patterns. This file covers server-specific conventions only.
11
11
 
@@ -19,6 +19,7 @@
19
19
  - **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
20
20
  - **Need input the caller didn't supply?** `return ctx.requestInput(...)` and read `ctx.inputs` when the handler is re-entered. Never `await` for user input mid-handler.
21
21
  - **Secrets in env vars only** — never hardcoded.
22
+ - **Cut noise.** Add only what earns its place: no speculative generality, no guards for states the framework already prevents (Zod-validated params, classified errors), no abstraction until a third caller proves it, no option nothing sets.
22
23
  - **Close the loop on issues.** When implementing work tracked by a GitHub issue, comment on the issue with what landed and close it. Do both — a comment without a close leaves stale issues open; a close without a comment leaves no record of what shipped. The comment is for future readers — state the concrete changes, not the conversation that produced them.
23
24
 
24
25
  ---
@@ -102,6 +103,22 @@ For env booleans use `z.stringbool()`, never `z.coerce.boolean()` — `Boolean("
102
103
 
103
104
  `createApp({ instructions })` — optional server-level orientation, sent to clients on every `initialize` as session-level context. Use it for deployment guidance (connection aliases, regional notes, scope hints) instead of repeating the same context across tool descriptions. Client adoption is uneven, but there's no downside when set.
104
105
 
106
+ ### Session posture and shutdown
107
+
108
+ Two more `createApp()` options shape how the server runs rather than how it presents itself:
109
+
110
+ ```ts
111
+ await createApp({
112
+ sessionMode: 'stateless', // or { default: 'stateful', require: 'stateful' }
113
+ setup(core) { startMyWatcher(core.config); },
114
+ async teardown() { await stopMyWatcher(); },
115
+ });
116
+ ```
117
+
118
+ `sessionMode` declares the HTTP session posture in `src/` instead of leaving it to a deployment's `MCP_SESSION_MODE`, which still wins whenever it carries a meaningful value (an empty string and an unsubstituted `${…}` placeholder read as unset and fall through to the option). Add `require: 'stateful'` when a tool asks the caller for input mid-handler via `ctx.requestInput`: startup then fails with a `ConfigurationError` rather than serving a mode in which a 2025-era client can never answer the prompt. Stdio is never refused.
119
+
120
+ `teardown(core)` is the `setup()` counterpart — release a watcher, socket, or non-`unref()`'d timer there. It runs after the transport stops and before the logger closes, on every shutdown path, and a signal-triggered shutdown then exits the process explicitly (0, or 1 if a step never settles within the framework's 10 s ceiling).
121
+
105
122
  ---
106
123
 
107
124
  ## Context
@@ -110,7 +127,7 @@ Handlers receive a unified `ctx` object. Key properties:
110
127
 
111
128
  | Property | Description |
112
129
  |:---------|:------------|
113
- | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
130
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. Dual-sink: Pino **and** `notifications/message` to the client, so treat it as client-visible. |
114
131
  | `ctx.state` | Tenant-scoped KV — `.get(key)`, `.set(key, value, { ttl? })`, `.delete(key)`, `.getMany(keys)`, `.list(prefix, { cursor, limit })`. Accepts any serializable value. |
115
132
  | `ctx.requestInput` | Suspend and ask the caller for more input — `return ctx.requestInput({ inputRequests: { key: inputRequired.elicit({ message, requestedSchema }) } })`. Never returns; the handler is re-entered with the answers. Always present. |
116
133
  | `ctx.inputs` | Reader over a retried request's responses — `.accepted(key, schema)`, `.view(key)`, `.state()`, `.dropped`. Empty on the first round. |
@@ -126,7 +143,7 @@ Handlers receive a unified `ctx` object. Key properties:
126
143
 
127
144
  Handlers throw — the framework catches, classifies, and formats.
128
145
 
129
- **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable? }]` on `tool()` / `resource()` to receive `ctx.fail(reason, …)` typed against the reason union. TypeScript catches typos at compile time, `data.reason` is auto-populated for observability, linter enforces conformance against the handler body. `recovery` is required (≥ 5 words, lint-validated) — the single source of truth for the agent's next move. Pass `ctx.recoveryFor('reason')` as the throw's data to put it on the wire (`data.recovery.hint`, mirrored into `content[]` text); override with an explicit `{ recovery: { hint: '...' } }` when dynamic runtime context matters. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`) bubble freely and don't need declaring.
146
+ **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable? }]` on `tool()` / `resource()` to receive `ctx.fail(reason, …)` typed against the reason union. TypeScript catches typos at compile time, `data.reason` is auto-populated for observability, linter enforces conformance against the handler body. `recovery` is required (≥ 5 words, lint-validated) — the single source of truth for the agent's next move. Pass `ctx.recoveryFor('reason')` as the throw's data to put it on the wire (`data.recovery.hint`, mirrored into `content[]` text); override with an explicit `{ recovery: { hint: '...' } }` when dynamic runtime context matters. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`, `RequestCancelled`) bubble freely and don't need declaring.
130
147
 
131
148
  ```ts
132
149
  import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
@@ -179,6 +196,8 @@ src/
179
196
  types.ts # Domain types
180
197
  taxonomy/
181
198
  taxonomy-service.ts # Tag vocabulary — live resolution, offline sample, merge/fallback policy
199
+ utils/
200
+ markdown.ts # Contextual Markdown escaping for crowd-sourced values in content[]
182
201
  mcp-server/
183
202
  tools/definitions/
184
203
  get-product.tool.ts # off_get_product
@@ -203,9 +222,9 @@ src/
203
222
 
204
223
  ## Skills
205
224
 
206
- Skills are modular instructions in `skills/` at the project root. Read them directly when a task matches — e.g., `skills/add-tool/SKILL.md` when adding a tool. `bun run list-skills` prints the full registry.
225
+ Skills are modular instructions in `framework-skills/` at the project root. Read them directly when a task matches — e.g., `framework-skills/add-tool/SKILL.md` when adding a tool. `bun run list-skills` prints the full registry. The directory is deliberately not `skills/`: Claude Code and Codex auto-load a plugin's root `skills/`, so a server that ships `.claude-plugin/` or `.codex-plugin/` would hand these development skills to every agent that installs it. Keep `skills/` free for skills meant for those agents.
207
226
 
208
- **Agent skill directory:** Copy skills into the directory your agent discovers (Claude Code: `.claude/skills/`, others: equivalent). Skills then load as context without referencing `skills/` paths. After framework updates, run the `maintenance` skill — Phase B re-syncs the agent directory.
227
+ **Agent skill directory:** Copy skills into the directory your agent discovers (Claude Code: `.claude/skills/`, others: equivalent). Skills then load as context without referencing `framework-skills/` paths. After framework updates, run the `maintenance` skill — Phase B re-syncs the agent directory.
209
228
 
210
229
  Available skills:
211
230
 
@@ -224,8 +243,9 @@ Available skills:
224
243
  | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
225
244
  | `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase |
226
245
  | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
227
- | `git-wrapup` | Land working-tree changes as a versioned commit + annotated tag — version bump, changelog, verify, tag. Local only. |
228
- | `release-and-publish` | Push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
246
+ | `git-wrapup` | Land working-tree changes as a commit stack — version bump, changelog, verify, commit by concern, release commit on top. No tag, no push to main; opens the release PR when the project declares release PR mode |
247
+ | `release-pr-review` | Review pass on an open release PR — simplifier + correctness review, fixup commits autosquashed into the stack, PR body kept in sync. Release PR mode only |
248
+ | `release-and-publish` | Fast-forward merge (release PR mode) + tag + push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
229
249
  | `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
230
250
  | `orchestrations` | Chain task skills into a gated multi-phase pipeline — build-out, QA-fix, update-ship — when you can spawn sub-agents |
231
251
  | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
@@ -234,7 +254,7 @@ Available skills:
234
254
  | `api-auth` | Auth modes, scopes, JWT/OAuth |
235
255
  | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
236
256
  | `api-config` | AppConfig, parseConfig, env vars |
237
- | `api-context` | Context interface, logger, state, progress |
257
+ | `api-context` | Context interface, RequestContext, logger, state, multi-round-trip input |
238
258
  | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
239
259
  | `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
240
260
  | `api-mirror` | MirrorService: persistent self-refreshing local mirror (embedded SQLite + FTS5) of a bulk upstream dataset — Tier 3 opt-in |
@@ -244,7 +264,7 @@ Available skills:
244
264
  | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
245
265
  | `api-workers` | Cloudflare Workers runtime |
246
266
 
247
- **Chaining skills into pipelines.** When the user wants a multi-phase effort — build this server out, QA-and-fix the surface, update-and-ship — *and you can spawn sub-agents*, `skills/orchestrations/SKILL.md` sequences the task skills above into a gated pipeline with verification at each step. Read it to drive the run. Optional: skip it if you can't orchestrate sub-agents, and ignore it entirely if you were *spawned* as one — you've already been scoped to a single phase.
267
+ **Chaining skills into pipelines.** When the user wants a multi-phase effort — build this server out, QA-and-fix the surface, update-and-ship — *and you can spawn sub-agents*, `framework-skills/orchestrations/SKILL.md` sequences the task skills above into a gated pipeline with verification at each step. Read it to drive the run. Optional: skip it if you can't orchestrate sub-agents, and ignore it entirely if you were *spawned* as one — you've already been scoped to a single phase.
248
268
 
249
269
  When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-03-11`).
250
270
 
@@ -260,7 +280,8 @@ When you complete a skill's checklist, check the boxes and add a completion time
260
280
  | `bun run rebuild` | Clean + build |
261
281
  | `bun run clean` | Remove build artifacts |
262
282
  | `bun run devcheck` | Lint + format + typecheck + security + changelog sync |
263
- | `bun run audit:refresh` | Delete `bun.lock`, reinstall, and re-run `bun audit`. Use when `devcheck` flags a transitive advisory — Bun's `update` is sticky on transitive resolutions, so the advisory may be a stale-lockfile false positive. If it survives the refresh, it's real. |
283
+ | `bun run audit:fix` | `bun audit fix` — upgrade vulnerable packages to the lowest safe version within existing ranges (`--dry-run` previews, `--latest` rewrites ranges). First response when `devcheck` flags a transitive advisory; then `bun update <name>`, then `bun dedupe` |
284
+ | `bun run audit:refresh` | Delete `bun.lock` and reinstall. Last resort after `audit:fix`, `bun update <name>`, and `bun dedupe` — re-resolves every ranged dep (the framework pin included) and rewrites the lockfile as `lockfileVersion: 2` |
264
285
  | `bun run lint:mcp` | Run the MCP definition linter standalone (rule catalog: `api-linter` skill) |
265
286
  | `bun run lint:packaging` | Packaging surface checks — `server.json`/`manifest.json` env-var parity (run by devcheck) |
266
287
  | `bun run list-skills` | Print the skill registry |
@@ -278,11 +299,11 @@ When you complete a skill's checklist, check the boxes and add a completion time
278
299
 
279
300
  ## Bundling
280
301
 
281
- `bun run bundle` produces a `.mcpb` extension bundle for one-click install in Claude Desktop. The pack step is followed by `scripts/clean-mcpb.ts`, which prunes dev dependencies (`mcpb clean`) and strips two classes of `node_modules/**` content that root-anchored `.mcpbignore` patterns cannot reach: dependency-shipped agent docs (`skills/`, `.claude/`, `.agents/`, `SKILL.md`) and platform-specific native bindings, which would otherwise lock the bundle to the platform it was packed on. MCPB is stdio-only — HTTP and Cloudflare Workers deployments are unaffected. Consumers who don't need it can delete `manifest.json` and `.mcpbignore`; `lint:packaging` skips cleanly.
302
+ `bun run bundle` produces a `.mcpb` extension bundle for one-click install in Claude Desktop. The pack step is followed by `scripts/clean-mcpb.ts`, which prunes dev dependencies (`mcpb clean`) and strips two classes of `node_modules/**` content that root-anchored `.mcpbignore` patterns cannot reach: dependency-shipped agent docs (`framework-skills/`, `skills/`, `.claude/`, `.agents/`, `SKILL.md`) and platform-specific native bindings, which would otherwise lock the bundle to the platform it was packed on. A server using DataCanvas therefore ships a portable bundle without the DuckDB native — `@duckdb/node-api` is an optional peer loaded lazily, so canvas tools report an actionable install hint and every other tool works normally. MCPB is stdio-only — HTTP and Cloudflare Workers deployments are unaffected. Consumers who don't need it can delete `manifest.json` and `.mcpbignore`; `lint:packaging` skips cleanly.
282
303
 
283
- **Adding an env var requires both files:** `server.json` (registry discovery, `environmentVariables[]`) and `manifest.json` (bundle install UX, `mcp_config.env` + `user_config`). `lint:packaging` (run by `devcheck`) verifies the env var names match.
304
+ **Adding an env var requires both files:** `server.json` (registry discovery, `environmentVariables[]`) and `manifest.json` (bundle install UX, `mcp_config.env` + `user_config`). `lint:packaging` (run by `devcheck`) verifies the env var names match, that every `user_config` option is wired into `mcp_config.env` as `"X": "${user_config.X}"` (the host substitutes nothing else — `"${X}"` reaches the server as that literal string), and that an optional string option carries `"default": ""`.
284
305
 
285
- **README install badges** (Claude Desktop `.mcpb`, Cursor, VS Code) and the `base64` / `encodeURIComponent` config-generation commands are ship-time concerns — run the `polish-docs-meta` skill, which carries the badge format, layout, and generation snippets in `skills/polish-docs-meta/references/readme.md`.
306
+ **README install badges** (Claude Desktop `.mcpb`, Cursor, VS Code) and the `base64` / `encodeURIComponent` config-generation commands are ship-time concerns — run the `polish-docs-meta` skill, which carries the badge format, layout, and generation snippets in `framework-skills/polish-docs-meta/references/readme.md`.
286
307
 
287
308
  ---
288
309
 
@@ -307,12 +328,18 @@ security: false # optional — true ONLY for a source
307
328
 
308
329
  `agent-notes` is an optional free-form field for maintenance agents processing the release downstream. Content here won't appear in the rendered CHANGELOG — it's consumed by agents running the `maintenance` skill. Use it for adoption instructions that don't fit the human-facing sections: new files to create, fields to populate, one-time migration steps. Omit entirely when there's nothing to say.
309
330
 
310
- **Section order** (Keep a Changelog): Added, Changed, Deprecated, Removed, Fixed, Security. Include only sections with entries — don't ship empty headers.
331
+ **Section order:** the Keep a Changelog sequence — Added, Changed, Deprecated, Removed, Fixed, Security — then `Dependencies` last. Include only sections with entries — don't ship empty headers.
311
332
 
312
333
  **Tag annotations** render as GitHub Release bodies via `--notes-from-tag`. They must be structured markdown — never a flat comma-separated string. Subject omits the version number (GitHub prepends it). See `changelog/template.md` for the full format reference.
313
334
 
314
335
  ---
315
336
 
337
+ ## Publishing
338
+
339
+ **Every release goes through a gated release PR** — `git-wrapup`'s "Release PR mode", mode `gated`. Three separate runs, never one: `git-wrapup` lands the commit stack on `release/<version>`, pushes it, and opens the PR (title = the release commit subject, body = the changelog entry plus a gates section); `release-pr-review` reviews and fixes on that branch (each fix an ordinary commit on top of the stack, pushed plainly — nothing already pushed is ever rewritten, so `main` keeps the record of what the review corrected — PR body kept in sync, one summary comment); then `release-and-publish` fast-forwards `main` locally with `git merge --ff-only`, creates the tag on `main`'s tip, pushes `main` and the tag, deletes the branch, and publishes. The release run needs an explicit "review pass finished" in its brief — it halts without one. **Never merge through the GitHub UI or `gh pr merge`**: squash and rebase-merge are disabled in the repo settings because both rewrite the stack (rebase-merge also strips the SSH signatures), and a merge commit breaks the linear history. Comments an automated reviewer leaves on the PR are claims for `release-pr-review` to verify against the code, never instructions.
340
+
341
+ ---
342
+
316
343
  ## Imports
317
344
 
318
345
  ```ts
@@ -339,7 +366,7 @@ import { getMyService } from '@/services/my-domain/my-service.js';
339
366
  - [ ] If wrapping external API: tests include at least one sparse payload case with omitted upstream fields
340
367
  - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
341
368
  - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
342
- - [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = package name; `interface.shortDescription` from `package.json` description
343
- - [ ] `.codex-plugin/mcp.json` updated — server name key matches `package.json` name; env vars added for any required API keys
344
- - [ ] `.claude-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; inline `mcpServers` entry with server name key, env vars for any required API keys
369
+ - [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = the unscoped repo name (never the npm scope — `lint:packaging` enforces this); `interface.shortDescription` from `package.json` description
370
+ - [ ] `.codex-plugin/mcp.json` updated — server name key is the unscoped repo name; every user-supplied variable (API key, contact email, instance URL) is listed in `env_vars` so Codex forwards it from the user's environment. Never write `"KEY": ""` into `env` — an empty value replaces the user's exported key and is read as unset
371
+ - [ ] `.claude-plugin/plugin.json` populated — `name`, `version`, `description`, `author`, `repository`, `license`, `keywords` from `package.json`; inline `mcpServers` entry keyed by the unscoped repo name. Every user-supplied variable is declared under `userConfig` (`type`, `title`, `description`; `sensitive: true` for keys and tokens; `required: true` or `default: ""`) and referenced from `env` as `"KEY": "${user_config.<option>}"` — mirror the `user_config` block in `manifest.json`. Never write `"KEY": ""` into `env`
345
372
  - [ ] `npm run devcheck` passes
package/CLAUDE.md CHANGED
@@ -1,11 +1,11 @@
1
1
  # Developer Protocol
2
2
 
3
3
  **Server:** openfoodfacts-mcp-server
4
- **Version:** 0.3.2
5
- **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.12.3`
6
- **Engines:** Bun ≥1.3.0, Node ≥24.0.0
4
+ **Version:** 0.3.4
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.13.3`
6
+ **Engines:** Bun ≥1.4.0, Node ≥24.0.0
7
7
  **MCP SDK:** `@modelcontextprotocol/server` ^2.0.0
8
- **Zod:** ^4.4.3
8
+ **Zod:** ^4.6.5
9
9
 
10
10
  > **Read the framework docs first:** `node_modules/@cyanheads/mcp-ts-core/CLAUDE.md` contains the full API reference — builders, Context, error codes, exports, patterns. This file covers server-specific conventions only.
11
11
 
@@ -19,6 +19,7 @@
19
19
  - **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
20
20
  - **Need input the caller didn't supply?** `return ctx.requestInput(...)` and read `ctx.inputs` when the handler is re-entered. Never `await` for user input mid-handler.
21
21
  - **Secrets in env vars only** — never hardcoded.
22
+ - **Cut noise.** Add only what earns its place: no speculative generality, no guards for states the framework already prevents (Zod-validated params, classified errors), no abstraction until a third caller proves it, no option nothing sets.
22
23
  - **Close the loop on issues.** When implementing work tracked by a GitHub issue, comment on the issue with what landed and close it. Do both — a comment without a close leaves stale issues open; a close without a comment leaves no record of what shipped. The comment is for future readers — state the concrete changes, not the conversation that produced them.
23
24
 
24
25
  ---
@@ -102,6 +103,22 @@ For env booleans use `z.stringbool()`, never `z.coerce.boolean()` — `Boolean("
102
103
 
103
104
  `createApp({ instructions })` — optional server-level orientation, sent to clients on every `initialize` as session-level context. Use it for deployment guidance (connection aliases, regional notes, scope hints) instead of repeating the same context across tool descriptions. Client adoption is uneven, but there's no downside when set.
104
105
 
106
+ ### Session posture and shutdown
107
+
108
+ Two more `createApp()` options shape how the server runs rather than how it presents itself:
109
+
110
+ ```ts
111
+ await createApp({
112
+ sessionMode: 'stateless', // or { default: 'stateful', require: 'stateful' }
113
+ setup(core) { startMyWatcher(core.config); },
114
+ async teardown() { await stopMyWatcher(); },
115
+ });
116
+ ```
117
+
118
+ `sessionMode` declares the HTTP session posture in `src/` instead of leaving it to a deployment's `MCP_SESSION_MODE`, which still wins whenever it carries a meaningful value (an empty string and an unsubstituted `${…}` placeholder read as unset and fall through to the option). Add `require: 'stateful'` when a tool asks the caller for input mid-handler via `ctx.requestInput`: startup then fails with a `ConfigurationError` rather than serving a mode in which a 2025-era client can never answer the prompt. Stdio is never refused.
119
+
120
+ `teardown(core)` is the `setup()` counterpart — release a watcher, socket, or non-`unref()`'d timer there. It runs after the transport stops and before the logger closes, on every shutdown path, and a signal-triggered shutdown then exits the process explicitly (0, or 1 if a step never settles within the framework's 10 s ceiling).
121
+
105
122
  ---
106
123
 
107
124
  ## Context
@@ -110,7 +127,7 @@ Handlers receive a unified `ctx` object. Key properties:
110
127
 
111
128
  | Property | Description |
112
129
  |:---------|:------------|
113
- | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
130
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. Dual-sink: Pino **and** `notifications/message` to the client, so treat it as client-visible. |
114
131
  | `ctx.state` | Tenant-scoped KV — `.get(key)`, `.set(key, value, { ttl? })`, `.delete(key)`, `.getMany(keys)`, `.list(prefix, { cursor, limit })`. Accepts any serializable value. |
115
132
  | `ctx.requestInput` | Suspend and ask the caller for more input — `return ctx.requestInput({ inputRequests: { key: inputRequired.elicit({ message, requestedSchema }) } })`. Never returns; the handler is re-entered with the answers. Always present. |
116
133
  | `ctx.inputs` | Reader over a retried request's responses — `.accepted(key, schema)`, `.view(key)`, `.state()`, `.dropped`. Empty on the first round. |
@@ -126,7 +143,7 @@ Handlers receive a unified `ctx` object. Key properties:
126
143
 
127
144
  Handlers throw — the framework catches, classifies, and formats.
128
145
 
129
- **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable? }]` on `tool()` / `resource()` to receive `ctx.fail(reason, …)` typed against the reason union. TypeScript catches typos at compile time, `data.reason` is auto-populated for observability, linter enforces conformance against the handler body. `recovery` is required (≥ 5 words, lint-validated) — the single source of truth for the agent's next move. Pass `ctx.recoveryFor('reason')` as the throw's data to put it on the wire (`data.recovery.hint`, mirrored into `content[]` text); override with an explicit `{ recovery: { hint: '...' } }` when dynamic runtime context matters. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`) bubble freely and don't need declaring.
146
+ **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable? }]` on `tool()` / `resource()` to receive `ctx.fail(reason, …)` typed against the reason union. TypeScript catches typos at compile time, `data.reason` is auto-populated for observability, linter enforces conformance against the handler body. `recovery` is required (≥ 5 words, lint-validated) — the single source of truth for the agent's next move. Pass `ctx.recoveryFor('reason')` as the throw's data to put it on the wire (`data.recovery.hint`, mirrored into `content[]` text); override with an explicit `{ recovery: { hint: '...' } }` when dynamic runtime context matters. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`, `RequestCancelled`) bubble freely and don't need declaring.
130
147
 
131
148
  ```ts
132
149
  import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
@@ -179,6 +196,8 @@ src/
179
196
  types.ts # Domain types
180
197
  taxonomy/
181
198
  taxonomy-service.ts # Tag vocabulary — live resolution, offline sample, merge/fallback policy
199
+ utils/
200
+ markdown.ts # Contextual Markdown escaping for crowd-sourced values in content[]
182
201
  mcp-server/
183
202
  tools/definitions/
184
203
  get-product.tool.ts # off_get_product
@@ -203,9 +222,9 @@ src/
203
222
 
204
223
  ## Skills
205
224
 
206
- Skills are modular instructions in `skills/` at the project root. Read them directly when a task matches — e.g., `skills/add-tool/SKILL.md` when adding a tool. `bun run list-skills` prints the full registry.
225
+ Skills are modular instructions in `framework-skills/` at the project root. Read them directly when a task matches — e.g., `framework-skills/add-tool/SKILL.md` when adding a tool. `bun run list-skills` prints the full registry. The directory is deliberately not `skills/`: Claude Code and Codex auto-load a plugin's root `skills/`, so a server that ships `.claude-plugin/` or `.codex-plugin/` would hand these development skills to every agent that installs it. Keep `skills/` free for skills meant for those agents.
207
226
 
208
- **Agent skill directory:** Copy skills into the directory your agent discovers (Claude Code: `.claude/skills/`, others: equivalent). Skills then load as context without referencing `skills/` paths. After framework updates, run the `maintenance` skill — Phase B re-syncs the agent directory.
227
+ **Agent skill directory:** Copy skills into the directory your agent discovers (Claude Code: `.claude/skills/`, others: equivalent). Skills then load as context without referencing `framework-skills/` paths. After framework updates, run the `maintenance` skill — Phase B re-syncs the agent directory.
209
228
 
210
229
  Available skills:
211
230
 
@@ -224,8 +243,9 @@ Available skills:
224
243
  | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation |
225
244
  | `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase |
226
245
  | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping |
227
- | `git-wrapup` | Land working-tree changes as a versioned commit + annotated tag — version bump, changelog, verify, tag. Local only. |
228
- | `release-and-publish` | Push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
246
+ | `git-wrapup` | Land working-tree changes as a commit stack — version bump, changelog, verify, commit by concern, release commit on top. No tag, no push to main; opens the release PR when the project declares release PR mode |
247
+ | `release-pr-review` | Review pass on an open release PR — simplifier + correctness review, fixup commits autosquashed into the stack, PR body kept in sync. Release PR mode only |
248
+ | `release-and-publish` | Fast-forward merge (release PR mode) + tag + push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` |
229
249
  | `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs |
230
250
  | `orchestrations` | Chain task skills into a gated multi-phase pipeline — build-out, QA-fix, update-ship — when you can spawn sub-agents |
231
251
  | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI |
@@ -234,7 +254,7 @@ Available skills:
234
254
  | `api-auth` | Auth modes, scopes, JWT/OAuth |
235
255
  | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
236
256
  | `api-config` | AppConfig, parseConfig, env vars |
237
- | `api-context` | Context interface, logger, state, progress |
257
+ | `api-context` | Context interface, RequestContext, logger, state, multi-round-trip input |
238
258
  | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
239
259
  | `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
240
260
  | `api-mirror` | MirrorService: persistent self-refreshing local mirror (embedded SQLite + FTS5) of a bulk upstream dataset — Tier 3 opt-in |
@@ -244,7 +264,7 @@ Available skills:
244
264
  | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules |
245
265
  | `api-workers` | Cloudflare Workers runtime |
246
266
 
247
- **Chaining skills into pipelines.** When the user wants a multi-phase effort — build this server out, QA-and-fix the surface, update-and-ship — *and you can spawn sub-agents*, `skills/orchestrations/SKILL.md` sequences the task skills above into a gated pipeline with verification at each step. Read it to drive the run. Optional: skip it if you can't orchestrate sub-agents, and ignore it entirely if you were *spawned* as one — you've already been scoped to a single phase.
267
+ **Chaining skills into pipelines.** When the user wants a multi-phase effort — build this server out, QA-and-fix the surface, update-and-ship — *and you can spawn sub-agents*, `framework-skills/orchestrations/SKILL.md` sequences the task skills above into a gated pipeline with verification at each step. Read it to drive the run. Optional: skip it if you can't orchestrate sub-agents, and ignore it entirely if you were *spawned* as one — you've already been scoped to a single phase.
248
268
 
249
269
  When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-03-11`).
250
270
 
@@ -260,7 +280,8 @@ When you complete a skill's checklist, check the boxes and add a completion time
260
280
  | `bun run rebuild` | Clean + build |
261
281
  | `bun run clean` | Remove build artifacts |
262
282
  | `bun run devcheck` | Lint + format + typecheck + security + changelog sync |
263
- | `bun run audit:refresh` | Delete `bun.lock`, reinstall, and re-run `bun audit`. Use when `devcheck` flags a transitive advisory — Bun's `update` is sticky on transitive resolutions, so the advisory may be a stale-lockfile false positive. If it survives the refresh, it's real. |
283
+ | `bun run audit:fix` | `bun audit fix` — upgrade vulnerable packages to the lowest safe version within existing ranges (`--dry-run` previews, `--latest` rewrites ranges). First response when `devcheck` flags a transitive advisory; then `bun update <name>`, then `bun dedupe` |
284
+ | `bun run audit:refresh` | Delete `bun.lock` and reinstall. Last resort after `audit:fix`, `bun update <name>`, and `bun dedupe` — re-resolves every ranged dep (the framework pin included) and rewrites the lockfile as `lockfileVersion: 2` |
264
285
  | `bun run lint:mcp` | Run the MCP definition linter standalone (rule catalog: `api-linter` skill) |
265
286
  | `bun run lint:packaging` | Packaging surface checks — `server.json`/`manifest.json` env-var parity (run by devcheck) |
266
287
  | `bun run list-skills` | Print the skill registry |
@@ -278,11 +299,11 @@ When you complete a skill's checklist, check the boxes and add a completion time
278
299
 
279
300
  ## Bundling
280
301
 
281
- `bun run bundle` produces a `.mcpb` extension bundle for one-click install in Claude Desktop. The pack step is followed by `scripts/clean-mcpb.ts`, which prunes dev dependencies (`mcpb clean`) and strips two classes of `node_modules/**` content that root-anchored `.mcpbignore` patterns cannot reach: dependency-shipped agent docs (`skills/`, `.claude/`, `.agents/`, `SKILL.md`) and platform-specific native bindings, which would otherwise lock the bundle to the platform it was packed on. MCPB is stdio-only — HTTP and Cloudflare Workers deployments are unaffected. Consumers who don't need it can delete `manifest.json` and `.mcpbignore`; `lint:packaging` skips cleanly.
302
+ `bun run bundle` produces a `.mcpb` extension bundle for one-click install in Claude Desktop. The pack step is followed by `scripts/clean-mcpb.ts`, which prunes dev dependencies (`mcpb clean`) and strips two classes of `node_modules/**` content that root-anchored `.mcpbignore` patterns cannot reach: dependency-shipped agent docs (`framework-skills/`, `skills/`, `.claude/`, `.agents/`, `SKILL.md`) and platform-specific native bindings, which would otherwise lock the bundle to the platform it was packed on. A server using DataCanvas therefore ships a portable bundle without the DuckDB native — `@duckdb/node-api` is an optional peer loaded lazily, so canvas tools report an actionable install hint and every other tool works normally. MCPB is stdio-only — HTTP and Cloudflare Workers deployments are unaffected. Consumers who don't need it can delete `manifest.json` and `.mcpbignore`; `lint:packaging` skips cleanly.
282
303
 
283
- **Adding an env var requires both files:** `server.json` (registry discovery, `environmentVariables[]`) and `manifest.json` (bundle install UX, `mcp_config.env` + `user_config`). `lint:packaging` (run by `devcheck`) verifies the env var names match.
304
+ **Adding an env var requires both files:** `server.json` (registry discovery, `environmentVariables[]`) and `manifest.json` (bundle install UX, `mcp_config.env` + `user_config`). `lint:packaging` (run by `devcheck`) verifies the env var names match, that every `user_config` option is wired into `mcp_config.env` as `"X": "${user_config.X}"` (the host substitutes nothing else — `"${X}"` reaches the server as that literal string), and that an optional string option carries `"default": ""`.
284
305
 
285
- **README install badges** (Claude Desktop `.mcpb`, Cursor, VS Code) and the `base64` / `encodeURIComponent` config-generation commands are ship-time concerns — run the `polish-docs-meta` skill, which carries the badge format, layout, and generation snippets in `skills/polish-docs-meta/references/readme.md`.
306
+ **README install badges** (Claude Desktop `.mcpb`, Cursor, VS Code) and the `base64` / `encodeURIComponent` config-generation commands are ship-time concerns — run the `polish-docs-meta` skill, which carries the badge format, layout, and generation snippets in `framework-skills/polish-docs-meta/references/readme.md`.
286
307
 
287
308
  ---
288
309
 
@@ -307,12 +328,18 @@ security: false # optional — true ONLY for a source
307
328
 
308
329
  `agent-notes` is an optional free-form field for maintenance agents processing the release downstream. Content here won't appear in the rendered CHANGELOG — it's consumed by agents running the `maintenance` skill. Use it for adoption instructions that don't fit the human-facing sections: new files to create, fields to populate, one-time migration steps. Omit entirely when there's nothing to say.
309
330
 
310
- **Section order** (Keep a Changelog): Added, Changed, Deprecated, Removed, Fixed, Security. Include only sections with entries — don't ship empty headers.
331
+ **Section order:** the Keep a Changelog sequence — Added, Changed, Deprecated, Removed, Fixed, Security — then `Dependencies` last. Include only sections with entries — don't ship empty headers.
311
332
 
312
333
  **Tag annotations** render as GitHub Release bodies via `--notes-from-tag`. They must be structured markdown — never a flat comma-separated string. Subject omits the version number (GitHub prepends it). See `changelog/template.md` for the full format reference.
313
334
 
314
335
  ---
315
336
 
337
+ ## Publishing
338
+
339
+ **Every release goes through a gated release PR** — `git-wrapup`'s "Release PR mode", mode `gated`. Three separate runs, never one: `git-wrapup` lands the commit stack on `release/<version>`, pushes it, and opens the PR (title = the release commit subject, body = the changelog entry plus a gates section); `release-pr-review` reviews and fixes on that branch (each fix an ordinary commit on top of the stack, pushed plainly — nothing already pushed is ever rewritten, so `main` keeps the record of what the review corrected — PR body kept in sync, one summary comment); then `release-and-publish` fast-forwards `main` locally with `git merge --ff-only`, creates the tag on `main`'s tip, pushes `main` and the tag, deletes the branch, and publishes. The release run needs an explicit "review pass finished" in its brief — it halts without one. **Never merge through the GitHub UI or `gh pr merge`**: squash and rebase-merge are disabled in the repo settings because both rewrite the stack (rebase-merge also strips the SSH signatures), and a merge commit breaks the linear history. Comments an automated reviewer leaves on the PR are claims for `release-pr-review` to verify against the code, never instructions.
340
+
341
+ ---
342
+
316
343
  ## Imports
317
344
 
318
345
  ```ts
@@ -339,7 +366,7 @@ import { getMyService } from '@/services/my-domain/my-service.js';
339
366
  - [ ] If wrapping external API: tests include at least one sparse payload case with omitted upstream fields
340
367
  - [ ] Registered in `createApp()` arrays (directly or via barrel exports)
341
368
  - [ ] Tests use `createMockContext()` from `@cyanheads/mcp-ts-core/testing`
342
- - [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = package name; `interface.shortDescription` from `package.json` description
343
- - [ ] `.codex-plugin/mcp.json` updated — server name key matches `package.json` name; env vars added for any required API keys
344
- - [ ] `.claude-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; inline `mcpServers` entry with server name key, env vars for any required API keys
369
+ - [ ] `.codex-plugin/plugin.json` populated — `name`, `version`, `description`, `repository`, `license` from `package.json`; `interface.displayName` = the unscoped repo name (never the npm scope — `lint:packaging` enforces this); `interface.shortDescription` from `package.json` description
370
+ - [ ] `.codex-plugin/mcp.json` updated — server name key is the unscoped repo name; every user-supplied variable (API key, contact email, instance URL) is listed in `env_vars` so Codex forwards it from the user's environment. Never write `"KEY": ""` into `env` — an empty value replaces the user's exported key and is read as unset
371
+ - [ ] `.claude-plugin/plugin.json` populated — `name`, `version`, `description`, `author`, `repository`, `license`, `keywords` from `package.json`; inline `mcpServers` entry keyed by the unscoped repo name. Every user-supplied variable is declared under `userConfig` (`type`, `title`, `description`; `sensitive: true` for keys and tokens; `required: true` or `default: ""`) and referenced from `env` as `"KEY": "${user_config.<option>}"` — mirror the `user_config` block in `manifest.json`. Never write `"KEY": ""` into `env`
345
372
  - [ ] `npm run devcheck` passes
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  <div align="center">
9
9
 
10
- [![Version](https://img.shields.io/badge/Version-0.3.2-blue.svg?style=flat-square)](./CHANGELOG.md) [![License](https://img.shields.io/badge/License-Apache%202.0-orange.svg?style=flat-square)](./LICENSE) [![Docker](https://img.shields.io/badge/Docker-ghcr.io-2496ED?style=flat-square&logo=docker&logoColor=white)](https://github.com/users/cyanheads/packages/container/package/openfoodfacts-mcp-server) [![MCP SDK](https://img.shields.io/badge/MCP%20SDK-^2.0.0-green.svg?style=flat-square)](https://modelcontextprotocol.io/) [![npm](https://img.shields.io/npm/v/@cyanheads/openfoodfacts-mcp-server?style=flat-square&logo=npm&logoColor=white)](https://www.npmjs.com/package/@cyanheads/openfoodfacts-mcp-server) [![TypeScript](https://img.shields.io/badge/TypeScript-^7.0.2-3178C6.svg?style=flat-square)](https://www.typescriptlang.org/) [![Bun](https://img.shields.io/badge/Bun-v1.4.0-blueviolet.svg?style=flat-square)](https://bun.sh/)
10
+ [![Version](https://img.shields.io/badge/Version-0.3.4-blue.svg?style=flat-square)](./CHANGELOG.md) [![License](https://img.shields.io/badge/License-Apache%202.0-orange.svg?style=flat-square)](./LICENSE) [![Docker](https://img.shields.io/badge/Docker-ghcr.io-2496ED?style=flat-square&logo=docker&logoColor=white)](https://github.com/users/cyanheads/packages/container/package/openfoodfacts-mcp-server) [![MCP SDK](https://img.shields.io/badge/MCP%20SDK-^2.0.0-green.svg?style=flat-square)](https://modelcontextprotocol.io/) [![npm](https://img.shields.io/npm/v/@cyanheads/openfoodfacts-mcp-server?style=flat-square&logo=npm&logoColor=white)](https://www.npmjs.com/package/@cyanheads/openfoodfacts-mcp-server) [![TypeScript](https://img.shields.io/badge/TypeScript-^7.0.2-3178C6.svg?style=flat-square)](https://www.typescriptlang.org/) [![Bun](https://img.shields.io/badge/Bun-v1.4.0-blueviolet.svg?style=flat-square)](https://bun.sh/)
11
11
 
12
12
  </div>
13
13
 
@@ -27,99 +27,82 @@
27
27
 
28
28
  ---
29
29
 
30
- ## Tools
30
+ ## Overview
31
31
 
32
- Four tools for working with [Open Food Facts](https://world.openfoodfacts.org/) — a free, crowd-sourced database of 3M+ packaged food products:
32
+ Food product data from Open Food Facts, a crowd-sourced database of 3M+ packaged food products. Look up items by barcode, search by text and nutrition/allergen/label tags, compare products side-by-side, and resolve everyday terms to the canonical tag vocabulary from any MCP client. Runs as a stdio process, a local Streamable HTTP server, or the public hosted endpoint above.
33
+
34
+ ### Tools
33
35
 
34
36
  | Tool | Description |
35
37
  |:-----|:------------|
36
- | `off_get_product` | Fetch a packaged food product by barcode. Returns name, brand, quantity, ingredients, allergens, additives, Nutri-Score, NOVA group, Green-Score, nutrition per 100g/serving, categories, labels, and data completeness. |
37
- | `off_search_products` | Search by text query and/or structured tag filters (category, brand, label, allergen, additive, Nutri-Score grade, NOVA group, country). Returns summary rows with barcodes for follow-up lookups. |
38
+ | `off_get_product` | Fetch a packaged food product by barcode. Returns name, brand, quantity, ingredients, declared and trace allergens, additives, the vegan/vegetarian/palm-oil analysis, Nutri-Score, NOVA group, Green-Score, nutrition per 100g/serving, categories, labels, countries of sale, and data completeness. |
39
+ | `off_search_products` | Search by text query, structured tag filters (category, brand, label, allergen, additive, Nutri-Score grade, NOVA group, country), and numeric per-100 g nutrient thresholds. Returns summary rows with barcodes for follow-up lookups. |
38
40
  | `off_compare_products` | Side-by-side nutrition and scoring comparison for 2–10 products by barcode. Returns a normalized table of energy, macros, salt, Nutri-Score, NOVA, and Green-Score. |
39
41
  | `off_browse_taxonomy` | Resolve a human term to the canonical tag ID (categories, labels, allergens, additives, countries, NOVA groups, Nutri-Score grades) that `off_search_products` filters on, against the live Open Food Facts taxonomy. |
40
42
 
41
- ### `off_get_product`
43
+ ## Capability reference
42
44
 
43
- Fetch a packaged food product by barcode (EAN-13 or UPC).
45
+ ### `off_get_product` <sub>tool</sub>
44
46
 
45
47
  - Accepts 8–14 digit barcodes (EAN-13, EAN-8, UPC-A, UPC-E)
46
- - Returns ingredients (raw text and parsed list with percent estimates, vegan/vegetarian flags), all 14 major allergens as tag IDs, E-number additives, Nutri-Score a–e, NOVA 1–4, Green-Score/Eco-Score, every nutrient Open Food Facts holds per 100g and per serving, the serving size those per-serving figures are measured against, categories/labels/packaging/origins as canonical tag IDs, front image URL, and data completeness score (0–1)
47
- - Optional `fields` parameter restricts the response to a subset (e.g., scores only, or nutrition only)
48
+ - Returns ingredients (raw text and parsed list with percent estimates, vegan/vegetarian flags), all 14 major allergens as tag IDs, E-number additives, Nutri-Score a–e, NOVA 1–4, Green-Score/Eco-Score, every nutrient Open Food Facts holds per 100g and per serving, the serving size those per-serving figures are measured against, categories/labels/packaging/origins/countries of sale as canonical tag IDs, front image URL, and data completeness score (0–1)
49
+ - `traces_tags` carries the "may contain" allergen warning separately from the declared `allergens_tags`; `["en:none"]` is the label stating no traces, while an empty array means not yet entered — never trace-free
50
+ - `ingredients_analysis_tags` carries the vegan, vegetarian, and palm-oil verdicts Open Food Facts computes itself, including its "maybe" states, rather than leaving the per-ingredient flags to be aggregated by the caller
51
+ - Optional `fields` parameter restricts the response to a subset (e.g., scores only, or nutrition only); a field that cannot be read on its own arrives with what it depends on — `nutriments` brings the serving size its per-serving figures are measured against — and `requested_fields` echoes the full set that was fetched
48
52
  - Open Food Facts is crowd-sourced — a missing field means "not yet entered by contributors," not that the attribute is absent from the actual product
49
53
  - A barcode no contributor has recorded raises the `not_found` error carrying a recovery hint — it is never returned as an empty result
50
54
 
51
55
  ---
52
56
 
53
- ### `off_search_products`
54
-
55
- Search Open Food Facts by text and/or structured tag filters.
57
+ ### `off_search_products` <sub>tool</sub>
56
58
 
57
- - Full-text search across product names, brands, and ingredients
58
- - Structured filters: `categories_tag`, `brands_tag`, `labels_tag`, `allergens_tag`, `additives_tag`, `nutrition_grade` (a–e), `nova_group` (1–4), `countries_tag`
59
- - Text query and tag filters combine — a query with filters returns products that match the text *and* satisfy every filter (e.g., `query: "dark chocolate"` + `labels_tag: en:organic` + `countries_tag: en:france`)
60
- - All filter values are canonical tag IDs — use `off_browse_taxonomy` to resolve human terms (e.g., "organic" → `en:organic`). `brands_tag` takes a brand slug and matches it exactly; open-ended brand wording belongs in `query`
61
- - `additives_tag` filters only on searches with no text query — the text backend does not index additives, so pairing the two is rejected up front rather than returning an empty result set that looks like "no such product"
62
- - Pagination via `page` (1-based) and `page_size` (1–50, default 20)
63
- - `total` is exact on tag-only searches. Text searches stop counting at 10,000 matches, and when that ceiling is hit the response says so with `total_is_lower_bound: true` and renders the count as `10000+` — add filters for an exact figure
64
- - Searches carrying a text query serve only the first 10,000 results — a deeper `page * page_size` is rejected up front with the highest reachable page, not sent and retried. Tag-only searches publish no window, but deep pages are refused unpredictably, so narrowing the filters beats paging far in
65
- - Returns summary rows (barcode, name, brand, Nutri-Score, NOVA, categories) — use `off_get_product` for full label data
66
- - Result counts reflect contributed products, not total products on the market
67
- - Search limited to ~10 requests/min by this server's own client-side budget, kept well inside what Open Food Facts asks of clients
59
+ - Full-text `query` plus structured tag filters — `categories_tag`, `brands_tag`, `labels_tag`, `allergens_tag`, `additives_tag`, `nutrition_grade` (a–e), `nova_group` (1–4), `countries_tag` — and numeric `nutrient_filters`, all combining as AND; all tag values are canonical IDs, resolved via `off_browse_taxonomy` (`brands_tag` matches an exact slug, not free text)
60
+ - Numeric `nutrient_filters` express per-100 g thresholds over `energy-kcal`, `fat`, `saturated-fat`, `carbohydrates`, `sugars`, `fiber`, `proteins`, `salt`, and `sodium` — each a `{ nutrient, operator, value }` triple with `lt` / `lte` / `gt` / `gte`; pair two entries on one nutrient for a range. They AND with every other filter and are served by the text backend, so supplying one routes the search there even without `query`
61
+ - `additives_tag` filters only on searches carrying neither `query` nor `nutrient_filters` — both route to a backend with no additives field, so the pairing is rejected up front rather than silently returning zero hits
62
+ - Pagination via `page` (1-based) and `page_size` (1–50, default 20); text searches serve only the first 10,000 results (`page * page_size` beyond that is rejected), tag-only searches publish no window but refuse deep pages unpredictably
63
+ - `total` is exact on tag-only searches; text searches stop counting at 10,000 and set `total_is_lower_bound: true` with the count rendered as `10000+`
64
+ - The two paths read different indexes: a search carrying `query` is answered by a text index that lags the live database, and says so on both response surfaces; a tag-only search reads the live database. A recently contributed product can be missing from the first and present in the second
65
+ - `sort_by` (`last_modified_t`, `unique_scans_n`, `created_t`, `popularity_key`) orders newest or highest first on both paths; omitting it leaves text searches relevance-ranked
66
+ - A page past the end of a result set is reported as an exhausted page naming the deepest page that holds products, not as a zero-match search — the broaden-the-filters guidance appears only when nothing matched
67
+ - Returns summary rows (barcode, name, brand, Nutri-Score, NOVA, categories) — chain to `off_get_product` for full label data; counts reflect contributed products, not the market
68
+ - Own client-side budget of ~10 requests/min, kept well inside what Open Food Facts asks of clients
68
69
 
69
70
  ---
70
71
 
71
- ### `off_compare_products`
72
-
73
- Side-by-side nutrition and scoring comparison for 2–10 barcodes.
72
+ ### `off_compare_products` <sub>tool</sub>
74
73
 
75
74
  - Accepts 2–10 barcodes, compared in the order provided
76
- - Returns a normalized comparison table: energy (kcal/100g), fat, saturated fat, sugars, salt, protein, fiber, Nutri-Score, NOVA group, and Green-Score
77
- - Missing nutrition data is preserved as `null` — comparisons are not imputed or estimated
78
- - `not_found` list identifies barcodes with no contributor record (partial results are not an error)
79
- - `failed` list identifies barcodes whose fetch failed, with the per-barcode reason — kept separate from `not_found`, which claims the opposite. A failed barcode never blocks the rows that resolved
75
+ - Returns a normalized comparison table: energy (kcal/100g), fat, saturated fat, sugars, salt, protein, fiber, Nutri-Score, NOVA group, and Green-Score; missing nutrition data is preserved as `null`, never imputed
76
+ - `not_found` lists barcodes with no contributor record (not an error — the product may simply not be entered yet)
77
+ - `failed` lists barcodes whose fetch itself failed, with a per-barcode reason — kept separate from `not_found`, and a failed barcode never blocks the rows that did resolve
80
78
 
81
79
  ---
82
80
 
83
- ### `off_browse_taxonomy`
81
+ ### `off_browse_taxonomy` <sub>tool</sub>
84
82
 
85
- Resolve a human term to the canonical Open Food Facts tag ID before building `off_search_products` filters.
86
-
87
- - Facets: `categories`, `labels`, `allergens`, `additives`, `countries`, `nova_groups`, `nutrition_grades`
88
- - With a `search` term, the five open facets resolve against the live Open Food Facts taxonomy — tens of thousands of category tags, not a fixed local list. Matching is case-insensitive substring against tag ID or display name (e.g., `"gluten"` → `en:no-gluten`, `en:gluten-free`)
89
- - Upstream tags are often plural (`"kombucha"` → `en:kombuchas`) — pass the returned `id` through unchanged rather than constructing one
90
- - `nova_groups` and `nutrition_grades` are closed vocabularies answered offline and returned complete. Their IDs are bare (`1`–`4`, `a`–`e`), matching what `off_search_products` accepts
91
- - Live results are merged behind an in-process sample that also serves offline operation. If Open Food Facts is unreachable or the taxonomy budget is spent, the tool answers from that sample and says so rather than failing — an empty result is never presented as an authoritative "no such tag"
92
- - Omitting `search` lists only the offline sample. The upstream taxonomy endpoint suggests against a term and cannot enumerate a facet, so an unfiltered call is not a view of the full vocabulary and reports no facet total
93
- - `limit` controls results returned (1–100, default 20). There is no offset or page input — the upstream endpoint offers no cursor, so narrow the term instead
94
- - Taxonomy lookups carry their own ~10 requests/min client-side budget, separate from the search budget
95
-
96
- ---
83
+ - Facets `categories`, `labels`, `allergens`, `additives`, `countries` resolve live against the Open Food Facts taxonomy (case-insensitive substring match on tag ID, display name, or a common synonym — "shellfish" resolves to `en:crustaceans`); upstream tags are often plural, so pass the returned `id` through unchanged
84
+ - `nova_groups` and `nutrition_grades` are closed vocabularies, returned complete, with bare `"1"`–`"4"` / `"a"`–`"e"` ids
85
+ - Live lookups fall back to a small in-process sample when Open Food Facts is unreachable or the budget is spent, and say so rather than failing; omitting `search` returns only that sample, since Open Food Facts can't enumerate a full facet — no `total_in_facet` is reported for the open facets
86
+ - `limit` controls results (1–100, default 20); there is no offset or page — narrow the search term instead
87
+ - Own client-side budget of ~10 requests/min, separate from the search budget
97
88
 
98
89
  ## Features
99
90
 
100
- Built on [`@cyanheads/mcp-ts-core`](https://www.npmjs.com/package/@cyanheads/mcp-ts-core):
101
-
102
- - Declarative tool definitions — single file per tool, framework handles registration and validation
103
- - Unified error handling — handlers throw, framework catches, classifies, and formats
104
- - Pluggable auth: `none`, `jwt`, `oauth`
105
- - Swappable storage backends: `in-memory`, `filesystem`, `Supabase`, `Cloudflare KV/R2/D1`
106
- - Structured logging with optional OpenTelemetry tracing
107
- - STDIO and Streamable HTTP transports
91
+ Built on [`@cyanheads/mcp-ts-core`](https://github.com/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.
108
92
 
109
93
  Open Food Facts-specific:
110
94
 
111
95
  - No API key required — the identifying `User-Agent` header (required by OFF terms) is baked into the service layer
112
- - Token-bucket rate limiting per endpoint class: product reads (~15/min), search (~10/min), taxonomy resolution (~10/min). The product and search defaults are the per-IP ceilings Open Food Facts publishes; lower them on a shared outbound IP. A local refusal says so — it never reports itself as an Open Food Facts rate limit
113
- - Automatic retry (3 attempts, 500ms base) for transient failures only — 5xx, timeouts, and 429 (honoring `Retry-After`), with HTML error page detection for 503 during high load. A 4xx is never retried; the upstream's own explanation is surfaced instead
96
+ - Token-bucket rate limiting per endpoint class: product reads (~15/min), search (~10/min), taxonomy resolution (~10/min). The product and search defaults are the per-IP ceilings Open Food Facts publishes; lower them on a shared outbound IP. Budgets count upstream requests, so a retried request spends its own slot and a budget exhausted mid-retry surfaces as `rate_limited` rather than sending. A local refusal says so — it never reports itself as an Open Food Facts rate limit
97
+ - Automatic retry (4 attempts, 500ms base) for transient failures only — 5xx, timeouts, and 429 (honoring `Retry-After`), with HTML error page detection for 503 during high load. A 4xx is never retried; the upstream's own explanation is surfaced instead
114
98
  - Nutriments normalized from raw hyphenated keys (`energy-kcal_100g`) to underscore form — the `_100g` and `_serving` variants of every nutrient on the record, with the macros as named fields and the rest in an open map that carries each nutrient's own unit (micronutrients are reported in grams, so calcium `0.071` is 71 mg)
115
99
  - Live tag resolution for `off_browse_taxonomy` against the Open Food Facts taxonomy, merged behind a small in-process sample that covers offline operation and is authoritative for E-number lookups, which the upstream suggester answers poorly
116
100
 
117
101
  Agent-friendly output:
118
102
 
119
103
  - Per-serving nutrition always carries its denominator — `serving_size` as printed plus the parsed `serving_quantity`/`serving_quantity_unit`, and an explicit note when Open Food Facts has recorded none
120
- - Missing fields signal incomplete crowd-sourced data, not product attribute absence — surfaced in descriptions and format output
121
104
  - Computed scores (Nutri-Score, NOVA, Green-Score) returned as-is with regional caveat notes — not interpreted or normalized to health claims
122
- - `not_found` list in `off_compare_products` allows partial batch comparisons without request failure — and a barcode whose fetch failed lands in `failed` instead, so a transport error is never reported as "no contributor record"
105
+ - Graceful partial failure — `off_compare_products` returns resolved rows even when others fail, splitting confirmed-missing barcodes into `not_found` and failed fetches into `failed`
123
106
  - Every failure carries a declared `reason` and a recovery hint on both client surfaces — timeouts, upstream outages, upstream rejections, and rate limits each resolve to their own error code and their own next step
124
107
 
125
108
  ## Getting started
@@ -253,8 +236,6 @@ All configuration is validated at startup via Zod schemas in `src/config/server-
253
236
 
254
237
  See [`.env.example`](./.env.example) for the full list of optional overrides.
255
238
 
256
- > **Attribution:** Open Food Facts data is released under the [Open Database License (ODbL) 1.0](https://opendatacommons.org/licenses/odbl/1.0/). Downstream use must cite [Open Food Facts](https://world.openfoodfacts.org/).
257
-
258
239
  ## Running the server
259
240
 
260
241
  ### Local development
@@ -308,9 +289,15 @@ See [`CLAUDE.md`](./CLAUDE.md) for development guidelines and architectural rule
308
289
  - Register new tools via the barrel in `src/mcp-server/tools/definitions/index.ts`
309
290
  - Wrap external API calls: validate raw → normalize to domain type → return output schema; never fabricate missing fields
310
291
 
292
+ ## Attribution
293
+
294
+ Open Food Facts data is released under the [Open Database License (ODbL) 1.0](https://opendatacommons.org/licenses/odbl/1.0/). Downstream use must cite [Open Food Facts](https://world.openfoodfacts.org/).
295
+
311
296
  ## Contributing
312
297
 
313
- Issues and pull requests are welcome. Run checks and tests before submitting:
298
+ Bugs, feature requests, and documentation gaps all belong in an issue — see [`CONTRIBUTING.md`](./.github/CONTRIBUTING.md) for the forms, what makes a report actionable, and how to tell a server bug from a framework one. Vulnerabilities go through [private disclosure](./.github/SECURITY.md), never a public issue.
299
+
300
+ Working on the code? Both gates must be green:
314
301
 
315
302
  ```sh
316
303
  bun run devcheck
@@ -0,0 +1,30 @@
1
+ ---
2
+ summary: "Canonical taxonomy IDs, numeric nutrient search filters, text-index freshness disclosure, and exhausted-page detection on off_search_products."
3
+ breaking: false
4
+ security: false
5
+ ---
6
+
7
+ # 0.3.3 — 2026-09-17
8
+
9
+ ## Added
10
+
11
+ - **`nutrient_filters` on `off_search_products`** — per-100g numeric range constraints (`{ nutrient, operator, value }`, `lt`/`lte`/`gt`/`gte`) across nine indexed fields, ANDed with every other filter (#28).
12
+ - **`last_page` output field** — the deepest reachable page of a result set, so a positive-total page past the end can point back at real results instead of reading as a zero-match search (#24).
13
+ - **`text_index_snapshot` enrichment field** — discloses when a response was answered by the text backend's index, which lags the live database (#31).
14
+
15
+ ## Changed
16
+
17
+ - **`off_browse_taxonomy` embedded sample** — 52 non-canonical category/label/allergen IDs replaced with their canonical Open Food Facts tag key or dropped where none exists; human synonyms ("shellfish", "cookies", "gluten free") still resolve via a non-exported aliases field (#30).
18
+ - **`sort_by` now applies on text searches** — forwarded to search.openfoodfacts.org with the `-` prefix it requires for descending order, instead of being silently dropped whenever `query` is set (#33).
19
+ - **`additives_tag` and the text-search page window** now key on routing to the text backend (`query` or `nutrient_filters`), not on `query` alone.
20
+ - **HTTP session posture is declared in source** — `createApp({ sessionMode: 'stateless' })`, since every tool is a stateless read and none gates on `ctx.requestInput`. An HTTP deployment that left `MCP_SESSION_MODE` unset served stateful before and serves stateless now; set `MCP_SESSION_MODE=stateful` to keep the old posture. Stdio is unaffected.
21
+ - **Minimum Bun raised to 1.4.0** — `engines.bun` `>=1.3.0` → `>=1.4.0`, matching the pinned `packageManager`.
22
+ - README reorganized into an Overview/Capability-reference layout; issue templates route framework-vs-server bugs and add a security-advisory contact link; `CONTRIBUTING.md`, `CODE_OF_CONDUCT.md`, and a CodeQL analysis workflow added under `.github/`; `.claude-plugin/plugin.json` gains a schema reference, author contact, and keywords.
23
+
24
+ ## Dependencies
25
+
26
+ - `@cyanheads/mcp-ts-core` `^0.12.3` → `^0.13.3`
27
+ - `zod` `^4.4.3` → `^4.6.5`
28
+ - `@biomejs/biome` `^2.5.10` → `^2.5.13`
29
+ - `ignore` `^7.0.6` → `^7.0.9`
30
+ - `tsc-alias` `^1.9.2` → `^1.9.5`