agentleFS
akutishevskyakutishevsky/nutrition-mcp/CLAUDE.md

nutrition-mcp

CLAUDE.md68 starsChanged 2 months agoMITView on GitHub

nutrition-mcp is a Model Context Protocol (MCP) server for nutrition-related functionality, built with Bun and TypeScript. Entry point is src/index.ts. It runs on MCP TypeScript SDK v2 (@modelcontextprotocol/server at runtime, @modelcontextprotocol/client only in tests) with Zod 4 as an explicit dependency; @modelcontextprotocol/sdk v1 is gone, so import McpServer, InMemoryTransport, createMcpHandler from @modelcontextprotocol/server. Every inputSchema / outputSchema here is a schema object (z.object({…})), never a raw shape: v2 still auto-wraps raw Zod 4 shapes via a deprecated overload, but the explicit…

  • Reads credentials
  • Commits and pushes
  • In this repositoryOne other file it gives its agents.

The file

We split this CLAUDE.md into the rules it gives an agent

4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Default to Bun for everything.

    line 54
  2. Very specific:

    Use HTML imports with Bun.serve() — not Vite.

    line 80
  3. Very specific:

    Logs carry redirect origins only: Every [oauth] … rejection logs one line with the client id and the redirect origin — never a full …

    line 199
  4. Very specific:

    Keep the pre-paint <script> right after <body> that applies the saved theme from localStorage — it is what prevents the light flash on …

    line 245

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

nutrition-mcp is a Model Context Protocol (MCP) server for nutrition-related functionality, built with Bun and TypeScript. Entry point is src/index.ts. It runs on MCP TypeScript SDK v2 (@modelcontextprotocol/server at runtime, @modelcontextprotocol/client only in tests) with Zod 4 as an explicit dependency; @modelcontextprotocol/sdk v1 is gone, so import McpServer, InMemoryTransport, createMcpHandler from @modelcontextprotocol/server. Every inputSchema / outputSchema here is a schema object (z.object({…})), never a raw shape: v2 still auto-wraps raw Zod 4 shapes via a deprecated overload, but the explicit form is the supported path, and it lets the exported *_OUTPUT_SCHEMA constants be .parse()d directly in tests. /mcp is a dual-era endpoint built on createMcpHandler (src/mcp.ts): it serves the 2026-07-28 revision (per-request _meta envelope, server/discover, no protocol-level sessions, Mcp-Method / Mcp-Name routing headers validated against the body) and, through the default legacy: "stateless" fallback, still answers 2025-11-25 clients with the same per-request initialize idiom the old hand-rolled transport used — one server factory backs both eras. The factory gets no Hono context: the authenticated user travels in the authInfo.extra.userId pass-through from handleMcp, and the public origin (for the icon URL) is read from ctx.requestInfo. The "/mcp over HTTP" section of src/mcp.test.ts drives both eras in-process by pointing a v2 Client's fetch at the Hono route — there is no in-memory transport for the modern era, so that is the only way to test it. It lives inside mcp.test.ts deliberately: mock.module is process-wide, and a separate file with its own mock/restore of ./supabase.js broke middleware.test.ts's mock on Linux CI (not reproducible on macOS). Two rules follow: stub ./supabase.js from an existing mock window rather than opening another, and restore from a snapshot taken before mock.module — Bun patches the namespace in place, so restoring from the live import is a no-op. listChanged is advertised false on purpose: the endpoint is stateless and refuses GET, so no channel exists to deliver a list-changed notification. Two v2 wire facts worth knowing: advertised schemas are JSON Schema 2020-12 (v1 stamped draft-07), and a POST whose Content-Type is not application/json is answered 415 before the body is read. Server version must be updated in three places: package.json, src/mcp.ts (McpServer constructor), and server.json. The server icon is at public/favicon.ico. Tool call analytics (duration, success/failure, error category) are tracked via src/analytics.ts and persisted to a tool_analytics Supabase table. Each row also carries protocol_era and client_name, because the runtime access log is a ring buffer holding well under an hour of traffic and cannot answer whether anyone still uses the 2025-era leg; retiring it is gated on select count(distinct user_id) from tool_analytics where protocol_era = 'legacy' and invoked_at > now() - interval '30 days' reaching zero — distinct users, over a window long enough to include people who log weekly. client_name is present on every modern call but only on a legacy initialize, since the stateless legacy leg builds a fresh server per request and only that one carries clientInfo. Runtime log lines (console.*) never carry a user id, email or per-user path; that is a privacy-policy promise, pinned by src/log-privacy.test.ts, and analyticsLogLine is the only analytics log formatter. Per-user questions go to tool_analytics.

Registered tool set. src/mcp.ts has 41 server.registerTool() calls; the number is hand-typed in a dozen places and every one must move together when a tool is added, removed, or renamed. Beyond src/mcp.test.ts and README.md's MCP Tools table, the count lives in src/copy/tools.ts's TOOLS identity array and its English prose (meta.title/meta.description/meta.ogDescription/hero.countBold, plus a doc comment cross-checking the number against mcp.ts), duplicated verbatim in src/copy/tools.<locale>.ts for all 8 locales; and in src/copy/index.ts's landing-page body copy (+ 8 locale files). The shared chrome (src/copy/chrome.ts, nav()/footer()) no longer carries the count — the redesigned sheet menu dropped the old toolsSmall pill — so only after every one of those is updated do scripts/gen-tools.ts and scripts/gen-index.ts need re-running. If the count ever goes back into nav()/footer(), all five generators have to re-run on every change (see "Generators" under Public site). Outside the repo, the directory listing names the tools too and needs its own reviewed edit (see "Claude directory listing"). "the registered tool set and every hand-typed tool count agree" in src/site-copy.test.ts guards most of it: it scrapes the server.registerTool("…") names out of mcp.ts (scraped, not imported, since building the server needs Supabase credentials), requires them to equal the names in TOOLS, and requires that number in every locale's four /tools count fields (meta.title/meta.description/meta.ogDescription/hero.countBold), every locale's landing-page onboarding.toolsCta.body, and public/llms.txt's "all N MCP tools". It was added after consolidating five settings-get_* tools into get_profile left stale counts that only a grep caught. README.md's table, the counts in src/mcp.test.ts and the directory listing are still checked by hand.

Every tool declares all five annotation fields; destructiveHint is true exactly for tools that overwrite or remove a user record (the delete_* tools, delete_account, update_meal, update_weight, update_body_measurement, set_nutrition_goals), and openWorldHint only for lookup_barcode — "every tool carries directory-ready annotations" in src/mcp.test.ts pins both sets. Model-facing text offers writes (update_meal backfills, set_* preferences) rather than directing them, and never asks for or infers a location the user did not state.

Deploying

This is a remote MCP server, and DigitalOcean auto-deploys main. Merging to main ships to production — there is no separate deploy step to run and no version bump or tag needed for a change to reach clients. Every client hitting https://nutrition-mcp.com/mcp picks it up as soon as the deploy finishes, so treat a merge as a release: prompt and tool-description edits go live exactly like code does, straight onto a directory-listed server (see "Claude directory listing" below).

Security contact. /.well-known/security.txt (RFC 9116) is built per request in src/security-txt.ts, not served from a static file, so Expires can't go stale: it is rolled 180 days ahead and truncated to UTC midnight, so the body is stable for a day. Canonical uses SITE, never the request host (getBaseUrl trusts x-forwarded-host). /security.txt 301s to it. The contact address sits between security-contact markers that scripts/depersonalize.ts blanks, and an empty contact makes the route 404 on forks. SECURITY.md is the human-readable policy (private reporting via GitHub advisories, which must stay enabled on the repo, plus the email); keep its address in sync with the one the site uses.

Claude directory listing

Since 2026-10-01 the server is listed in Anthropic's connectors directory (Community label) at https://claude.ai/directory/nutrition-mcp, the URL the landing page's "Add to Claude" button (CLAUDE_DIRECTORY_URL in scripts/gen-index.ts), the /alternatives install steps and FAQ, README.md and llms.txt link (scripts/depersonalize.ts swaps it for a placeholder, since it connects to this server). A listed server must keep meeting the Software Directory Policy and the review criteria, and nothing re-checks it: a tool change is never resubmitted, so deploying to main is the release, and Anthropic can delist a server that drifts. Every change is held to that bar:

  • Model-facing text describes; it never directs. Tool descriptions and titles, tool results and SERVER_INSTRUCTIONS say what a tool does and when it applies, and must match what it actually does. They never tell Claude how to behave, never steer it toward a tool the user didn't ask for or away from another server's tools, never pull instructions from an external source, never carry hidden or encoded instructions, and never promote anything (no Patreon or other plugs in model-facing text). The approval review flagged "offer …" and "narrate …" phrasing addressed to the assistant even after earlier rounds had softened "direct" to "offer"; fixed in #190.
  • Tool shape. Names stay ≤64 characters; read and write stay separate tools (no catch-all tool taking a method or action switch); every tool keeps its title and annotations, which Claude uses for auto-permissions (read-only tools run without a prompt, destructive ones always prompt) — "every tool carries directory-ready annotations" in src/mcp.test.ts pins them.
  • Errors and size. A failure returns an actionable message, never a bare "Internal Server Error" (ToolError / userFacingError); inputs are validated, not silently accepted. Responses stay proportional to the request (compact listings, MEAL_LISTING_MAX_CHARS, range caps). The listing's health badge counts 5xx responses, timeouts and isError: true results against tool calls over 30 days (Healthy is ≤2%, Degraded >5%), visible at claude.ai/directory/manage.
  • Data and scope. Collect nothing from the conversation beyond what a tool needs, and never ask for Claude's memory, chat history or files. No payments or asset transfers, no AI-generated images, video or audio (the hand-built SVG charts are fine), no ads or sponsored content. OAuth 2.0 over HTTPS and Streamable HTTP stay as they are.
  • Developer obligations. The privacy policy, terms, support contact (SECURITY.md / security.txt address), public docs (/tools and its troubleshooting section) and the reviewers' test account with sample data must keep working; issues get fixed promptly.
  • Listing edits are separate from deploys. Tool names shown on the listing are listing metadata, so adding, renaming or removing a tool also needs a listing edit in the dashboard (another item for the tool-count checklist under "Registered tool set"), which a reviewer approves. Changing the display name requires re-review; the slug is permanent. Anything the dashboard can't edit (e.g. the use-case prompts), and delisting, go to mcp-review@anthropic.com.

Publishing to the registry

Separate from deploying, and rarely required. The MCP Registry is only discovery metadata pointing at https://nutrition-mcp.com/mcp, so a fix takes effect without republishing. To refresh the registry listing on a release, bump the version in all three places above, merge to main, then push a matching v* tag:

git tag v1.13.3 && git push origin v1.13.3

The .github/workflows/publish-mcp.yml workflow then runs the tests, verifies the tag matches server.json's version, and publishes via mcp-publisher using GitHub OIDC (no secrets). Each published version must be unique and is immutable once published, so always tag a fresh version — never re-tag an already-published one.

Commands

  • bun run src/index.ts - Run the server
  • bun --watch src/index.ts - Run with watch mode (restarts on file changes)
  • bun test - Run all tests
  • bun test src/path/to/file.test.ts - Run a single test file
  • bun run format - Format code with Prettier (4-space indentation)
  • bun run format:check - Verify the tree is prettier-clean (CI runs this on every PR)
  • bun run typecheck - Typecheck src/ (CI runs this on every PR). tsconfig.json has no include, so tsc checks the whole project and scripts/typecheck.ts keeps only the src/ diagnostics: src/**/*.test.ts is checked, a type error under scripts/ is not

The committed tree is kept prettier-clean, so bun run format only rewrites files you actually edited. Generated output that must not be formatted goes in .prettierignore.

Bun Runtime

Default to Bun for everything. Do not use Node.js equivalents.

  • bun <file> instead of node/ts-node
  • bun install instead of npm install
  • bun run <script> instead of npm run
  • bunx <pkg> instead of npx
  • Bun auto-loads .env — don't use dotenv

Preferred Bun APIs

  • Bun.serve() for HTTP/WebSocket servers (not Express)
  • bun:sqlite for SQLite (not better-sqlite3)
  • Bun.redis for Redis (not ioredis)
  • Bun.sql for Postgres (not pg/postgres.js)
  • Bun.file for file I/O (not node:fs readFile/writeFile)
  • Bun.$\cmd`` for shell commands (not execa)
  • Built-in WebSocket (not ws)

Testing

import { test, expect } from "bun:test";

Frontend (if needed)

Use HTML imports with Bun.serve() — not Vite. HTML files can directly import .tsx/.jsx/.js and Bun bundles automatically. Bun API docs: node_modules/bun-types/docs/**.mdx.


Custom UI Widgets (MCP Apps)

In-chat UI uses MCP Apps (the official 2026-01-26 MCP extension), which renders across Claude, ChatGPT, VS Code, Goose, and MCP Inspector from one implementation. Widgets are assembled from source partials at server startup — not committed as built files. Sources live in public/widgets/src/ (shared/ partials + one templates/*.html per widget); src/widgets.ts inlines the partials (resolving /*@include shared/…@*/ markers) into one self-contained HTML string per widget, cached and warmed at boot (warmWidgets() in src/index.ts). src/mcp.ts serves each via getWidgetHtml(key). Every in-chat widget is one compact card: a header line, the widget's own top matter (a chart, a range toggle, a weight line), then the shared macro strip — a calorie ring beside its figure, three macro bars, a "limits" row (sugar / alcohol / caffeine / fiber), and the water line. The shell lives in shared/base.css (.wrap.tight, .panel, .phead, .psec) and the strip in shared/macros.*. The widgets: the get_nutrition_summary dashboard, the get_goal_progress view, the meal-progress strip (meal-logged, which renders nothing when no goals are set), the get_trends view (interactive 7/14/30-day toggle), the get_weight_trends view (data-scaled weight-over-time chart with the same toggle), and import-meals (the bulk-import flow — see "Bulk meal import" below). component-gallery is dev-only: it is listed in WIDGET_TEMPLATES so it is assembled and test-covered, but no ui:// resource or tool references it, so no client can reach it — view it with bun run harness. They share one design language and one host bridge — see public/widgets/STYLE_GUIDE.md. bun test src/widgets.test.ts guards assembly (no unresolved markers, valid inline JS, every partial inlined in full).

A second marker, /*@inlinets src/csv.ts@*/, transpiles a TypeScript module from src/ into the widget as plain JS. It exists so a widget can run tested server-side code instead of a hand-copied twin; it only works for modules with no runtime imports, and it strips module syntax because a bare export inside a <script> is a syntax error.

Widget UI language. set_language persists to profiles.locale; there is no standalone get_language — get_profile reports it in one line alongside timezone/weight unit/etc. (localeFromProfile/getUserLocale in src/supabase.ts, default "en"). get_nutrition_summary's structuredContent.locale is that resolved value, read server-side so the widget renders its own strings without a second round trip — z.string(), not z.enum(SITE_LOCALES), since SITE_LOCALES is a readonly SiteLocale[] and getUserLocale's fallback is what actually guarantees a known code.

A third assembly marker, /*@i18n@*/ (src/widgets.ts), inlines the whole WIDGET_STRINGS dictionary (src/copy/widgets.ts, one widgets.<locale>.ts per locale, like chrome.ts) as a JSON.stringify'd const — plain data only, since that's exactly what gets spliced in. It deliberately does not live inside shared/i18n.js itself: it sits once per template, immediately before that template's own /*@include shared/i18n.js@*/ line, because src/widgets.test.ts requires every @included partial's full text to appear verbatim in the assembled HTML, and the assembler's marker regexes match plain text — comments included — so a /*@i18n@*/ sitting inside i18n.js would get replaced away and break that check, or self-include the very partial defining it (the same reason shared/macros.js hand-copies DRINK_GRAMS rather than pulling it in with @inlinets).

shared/i18n.js resolves which locale to render, exposed as the ambient T (mirroring data-theme as ambient theme rather than a threaded argument): pickLocale(explicit, hostLocale) prefers structuredContent.locale — per-user, always set — over the host's hostContext.locale — host-dependent, may be absent — over "en", matched on BCP-47 base language. A template calls setLocale() from its render() once the payload's locale is known. WidgetStrings is plain strings except PluralForms ({ one, other }), picked via Intl.PluralRules — a browser built-in, no network request, so it's fine under the iframe's default-src 'none' CSP — falling back to other for any category the 2-form data lacks, consistent with translation here being AI-generated with no human review pass (same as the public site's — see below).

Every widget except component-gallery (dev-only, unreachable by any client) is fully wired end-to-end. nutrition-summary, goal-progress, meal-logged, trends, weight-trends, and import-meals each call setLocale(pickLocale(structuredContent.locale, hostContext.locale)) from render() (or, for import-meals, from the initWidget config's outer render(data) callback, since its own internal render() repaints steps without fresh data) and have their own WidgetStrings namespace (goalProgress, mealLogged, trends, weightTrends, importMeals) alongside macros/nutritionSummary, translated into every locale. weight-trends and import-meals didn't carry the @i18n machinery at all until this was added — they now @include shared/i18n.js like the others. Every tool whose widget needs it (get_goal_progress, log_meal/update_meal via buildMealProgress, get_trends, get_weight_trends, start_meal_import) resolves locale via getUserLocale/localeFromProfile and includes it in structuredContent, mirroring get_nutrition_summary's original field. Two deliberate non-translations, not gaps: import-meals's diagnosticsBlock() copy-paste support-email dump stays English (addressed to the English-speaking maintainer, not the widget's audience), and api.updateModelContext's finished-import summary stays English (model-facing text like every tool's content, not UI) — see the doc comment on importMeals in src/copy/widgets.ts. Extending a widget further is: call setLocale() from render()/onReady() as these do, and add its strings to WidgetStrings (every locale file) alongside the existing keys.

bun run harness is the local host simulator (scripts/widget-harness.ts). It mimics a strict host — validates the ui/initialize shape, withholds the tool result until ui/notifications/initialized, starts the iframe at 130px, applies the sandbox CSP — and additionally answers app-initiated tools/call, sends host→app requests, and executes the real bulk_import_meals against an in-memory store. Query flags reproduce host behaviour: ?serverTools=0, ?tools=0, ?delay=3000, ?maxHeight=600, ?fail=1.

Interactive widgets slice client-side. trends.html has a 7/14/30-day toggle: rather than round-trip to re-call the tool, get_trends sends up to 30 days of daily series and the widget slices/re-averages/re-renders locally, so switching ranges is instant and needs no host tool-call support. Prefer this pattern (send a superset, filter in the widget) for range/filter toggles.

One widget can back several tools. meal-logged.html is linked by both log_meal and update_meal: both declare outputSchema: MEAL_PROGRESS_OUTPUT_SCHEMA and build their structuredContent through the shared buildMealProgress() helper, so the payload shape is identical; the action field ("logged" / "updated") only changes the widget's header. To reuse a widget across tools, point each tool's _meta.ui.resourceUri at the same ui:// URI and keep their structuredContent shapes identical.

Server wiring (src/mcp.ts):

  • An advertised outputSchema is frozen once it is deployed. Hosts (claude.ai, Claude Desktop) cache tools/list for an unknown, possibly multi-day period and validate every structuredContent against the cached schema, and Zod 4 emits additionalProperties: false on every object — so adding a field, even an optional one, fails the whole call ("Structured content does not match the tool's output schema: data must NOT have additional properties") for every user with a stale list, and removing or narrowing one breaks them the other way. New widget-only data goes in the CallToolResult's _meta under a nutrition-mcp.com/… key (not validated against outputSchema, "not intended for model context", and delivered to the view whole in ui/notifications/tool-result); new model-facing data goes in content. src/output-schemas.frozen.json pins every tool's advertised schema, checked by the "output schemas are frozen once deployed" test in src/mcp.test.ts; rewriting it (UPDATE_OUTPUT_SCHEMAS=1 bun test src/mcp.test.ts -t "output schemas", which also runs prettier on the file so format:check stays green) is a deliberate decision that needs a compatibility plan, never a way to make the test pass. A new tool's schema is frozen from its first deploy. The schema pin alone would not catch a handler that returns an extra key without touching the schema (the server's Zod parse ignores unknown keys), so withTools and withHttpClient in src/mcp.test.ts call listTools() before any callTool: the v2 Client then checks every structuredContent against the advertised strict JSON Schema, as a host does.
  • Register the widget HTML as a resource with a ui:// URI and mimeType text/html;profile=mcp-app (see the SUMMARY_WIDGET_URI / APP_UI_MIME_TYPE constants). Serve it via getWidgetHtml("<key>") (from src/widgets.ts), which returns the assembled, fully-inlined document. To add a widget: create public/widgets/src/templates/<key>.html (reuse @include shared/… partials + call initWidget({…})), add the key to WIDGET_TEMPLATES in src/widgets.ts, and register the resource here.
  • Link it on the tool config: _meta: { ui: { resourceUri: "ui://..." } }. The SDK supports _meta and outputSchema on registerTool.
  • The tool must return structuredContent (declare an outputSchema and return it on every path — this then emits structuredContent for all clients, not just UI ones). The widget renders from structuredContent; content remains the model-facing text.

The assembled widget is a single self-contained HTML — inline CSS + JS, zero network requests. The iframe CSP defaults to deny-all (default-src 'none'): no CDN/external scripts, and eval/new Function are blocked. It is a default, not a hard limit — the apps spec defines _meta.ui.csp / hostCapabilities.sandbox.csp with connectDomains, resourceDomains, frameDomains and baseUriDomains — but nothing here needs relaxing it, and self-contained is still the right default. Worth knowing what the CSP does not cover: <input type="file"> and FileReader work fine under it, because reading a local file is not a network fetch (tested under sandbox="allow-scripts" plus default-src 'none') — which is what makes the in-browser CSV parse in import-meals possible.

Because external scripts and stylesheets are out, reuse happens inline-at-build-time (the @include assembler) rather than through a linkable stylesheet or <script src>. To use a chart library, inline it the same way; we use hand-built SVG instead (0 KB, follows CSS light/dark vars natively via currentColor / var(--…)).

Styling — reuse the shared design language. All widgets share one look (Apple-like neutral surfaces, brand green accent, theme tokens, one compact card per widget, a donut gauge, thin metric bars, SVG trend charts). Layout inside the strip is driven by each MACROS entry's role in shared/macros.js (cal / macro / limit / bar) — never by a hardcoded key list, so a new nutrient appears exactly where its role says and nowhere else. The tokens and component CSS live as source partials in public/widgets/src/shared/ and are inlined via @include; public/widgets/STYLE_GUIDE.md is the spec for those partials. Edit a partial once and every widget picks it up on next assembly — do not re-inline or fork a shared block into a template. Keep the JS host handshake in shared/bridge.js (initWidget(config)); a template supplies { name, loading, coerce, render, sample }, plus an optional onReady(api) when it needs to call the server. api exposes callTool(name, args, opts), canCallTools (whether the host advertised hostCapabilities.serverTools), hostContext, hostInfo, and updateModelContext(text). Form controls and the preview table live in shared/form.css and shared/table.css; .card is the shared surface in shared/base.css.

Two bridge invariants that are easy to break: a message is only treated as a response to our request when it has no method and carries result/error (the host sends its own requests, with its own id counter — the spec's ui/resource-teardown example uses id: 1, which is why our ids are namespaced app-N), and inbound messages are rejected unless event.source === host (window.parent.frames is reachable cross-origin, so a sibling iframe could otherwise forge a tool result and repaint a widget).

The iframe→host handshake must be exact. Strict hosts (MCP Inspector) validate the request shape and silently drop malformed ones — symptom: widget stuck on "Loading…" while the tool succeeds server-side. Sequence over plain window.postMessage(msg, "*") to window.parent:

  1. App → host: ui/initialize request. Params use appInfo and appCapabilities — NOT the MCP-core clientInfo / capabilities (this exact mix-up was the original bug): { protocolVersion: "2026-01-26", appInfo: {name, version}, appCapabilities: {} }.
  2. host → app: JSON-RPC response (host context incl. theme at result.hostContext.theme).
  3. App → host: ui/notifications/initialized notification (no params). Required — without it strict hosts never send the result.
  4. host → app: ui/notifications/tool-result notification with params.structuredContent → render. Only show the built-in sample fallback when there is no host (window.parent === window), never inside one.

The widget MUST report its height, or the host clips it. The host gives the iframe a small default height and only grows it when the app sends ui/notifications/size-changed with { width, height }. Without it the widget renders fine but is cut off after the first row (this was a shipped bug). Measure the natural height by temporarily setting document.documentElement.style.height = "max-content", reading getBoundingClientRect().height, then restoring; width is window.innerWidth. Wire a ResizeObserver (debounced with requestAnimationFrame) on documentElement + body so it re-reports after the tool-result render and after any interactive re-render (e.g. a toggle). Do not rely on body { min-height: 100vh } for sizing — it fights content-based measurement; let the body size to its content. Test with a host-harness that starts the iframe SHORT (~130px) and grows it on size-changed — a fixed-tall test iframe hides this bug entirely.

Ground truth when in doubt: the reference SDK @modelcontextprotocol/ext-apps — src/app.ts connect() shows the exact initialize request; dist/src/generated/schema.json lists all ui/* method names. Spec: https://blog.modelcontextprotocol.io/posts/2026-01-26-mcp-apps/, repo: https://github.com/modelcontextprotocol/ext-apps. Alternative to hand-rolling: bundle that package's App class inline (~100 KB, but tracks the spec). Verify without a real client using a local host-harness HTML that embeds the widget in a sandbox="allow-scripts" iframe, mimics the strict host, and pushes distinct data via postMessage.


Bulk meal import

Two entry points, one write path.

  • start_meal_import returns the import-meals widget. Prefer it whenever the user has an actual file: the widget parses and maps the export in the browser, so rows never pass through the model and cannot be mistranscribed. Its outputSchema is load-bearing — with no structuredContent the bridge never paints and the iframe sits on its loading state — and it carries tz so the widget's preview matches what the server will store.
  • bulk_import_meals is the universal fallback, callable by the model and by the widget (default _meta.ui.visibility is ["model", "app"], so one tool serves both; ["app"] would hide it from the model and break users who have widgets disabled).

src/import.ts holds the logic, free of Supabase so it unit-tests with fixtures; src/mcp.ts is a thin adapter supplying insert and existingKeys. src/csv.ts is the parser, inlined into the widget via @inlinets.

Non-obvious invariants, each of which was a real bug or nearly one:

  • Rows carry an explicit import:<digest>:<ordinal> idempotency key. insertMeal derives a content hash when none is given, and that hash includes logged_at — but date-only rows all anchor at local noon, so two genuinely separate identical rows hashed alike and the second was silently swallowed as deduplicated while the control total still reconciled. The ordinal counts preceding identical rows in the same call, so replaying a file is still a perfect no-op. It is the ordinal and not source_line, so re-exporting a file with lines added still dedupes. Never split a calendar date across calls — the ordinal is per call. The digest hashes the resolved instant, so a timezone change between two sends re-resolves every offset-less row that has neither a source_id nor its own timezone to a new key, and the second send inserts those again (own-export rows, keyed and deduplicated by id and resolved in their own zone, are unaffected); the tool text says so (the no-timezone warning's real-import branch never advises re-importing, and SERVER_INSTRUCTIONS qualifies "re-sending is safe" on the timezone being unchanged).
  • Our own export re-imports by id, not by content. The content digest structurally cannot recognize a meal coming back in: log_meal writes auto:<digest> keys and the importer writes import:… ones, and the two hash different renderings of logged_at (the export emits second-precision local wall time, which the importer then re-resolves). So every row carries an optional source_id — the id column of the meals.csv our own export writes — and a row naming a meal the user still has is reported deduplicated without an insert, on the dry-run path and the real one alike. Rows whose meal was since deleted key on import:src:<uuid>:<ordinal> so a second replay is still a no-op. Only uuid-shaped values count: a foreign app's id column is dropped rather than rejected, and passing a non-uuid to the uuid-typed in ("id", …) lookup would fail the whole batch on a cast error rather than simply not matching. The export's timezone column closes the other half of that gap: a row whose meal was since deleted — the actual "restore my data" case — still gets written fresh rather than deduplicated by id, so it also carries an optional timezone field (mapped by the widget from the export's own timezone column), which resolveLoggedAt uses in place of the account's current timezone when present and valid — otherwise an offset-less wall clock silently re-resolves against whatever timezone the account has now, moving the meal to a different local day (#97).
  • The tool never sets isError. Failure is status: "failed" inside the outputSchema. isError short-circuits the SDK's output validation and hosts commonly surface only content, which would drop the per-row report that is the whole product. Consequence: withAnalytics needs its outcome callback, or failed imports log as successes.
  • .nullable() is not optional. Nullable fields are emitted as required with an anyOf[type, null] value, so every result row must be built from a complete literal with explicit nulls. src/import.test.ts validates the serializer against the schema — the only guard, since bun run typecheck covers src/ but not the shape a handler actually returns at runtime.
  • Bounds live in the handler, not in Zod. A schema-level rejection happens before the handler runs, discarding the structured report, the warnings and the analytics row — for what will be the caller's most common mistake. Numbers use z.coerce like log_meal.
  • Timestamps accept a bare date (→ local noon), an offset-less local time (resolved in the profile timezone), or full ISO with an offset. Offset-less is accepted deliberately: no fitness export carries an offset, so requiring one forces the caller to compute historical DST per row. Every resolved date asserts the dateInTz round trip, which turns never-existed local dates (Pacific/Apia 2011-12-30) into explicit errors. An unconfigured timezone silently means UTC, so the tool warns — a missing profiles row is the only reliable "never set" signal.
  • Every write path resolves logged_at through the same parseLoggedAt in src/tz.ts — the importer via resolveLoggedAt (src/import.ts), the seven manual tools (log_meal, update_meal, log_water, log_weight, update_weight, log_body_measurement, update_body_measurement) via resolveWriteLoggedAt and the resolveWriteTimestamp adapter in src/mcp.ts. Handing an offset-less string to the timestamptz column instead reads it in the DB session zone (UTC), which filed a Kyiv user's 21:00 meal at 00:00 the next day while the tool's own progress line reported the later date (issue #68). The two callers differ only in bounds: the importer is backfilling and takes 20 years back to 48 hours ahead; a manual entry has no past bound and a 5-minute future one, except a bare date, whose local-noon anchor is a placeholder for an unknown time and so is judged by calendar day. This is not about cross-route dedupe — the importer stamps import: keys and never reaches the auto: digest — it is about both routes filing the same string on the same local day, since every read path buckets by dateInTz. An omitted logged_at is stamped at arrival, so the derived auto: key dedupes only replays that carry an explicit logged_at or a caller-supplied idempotency_key; tool text must not promise more than that (idempotencyKeyDescription in src/mcp.ts), and bucketing the arrival time was rejected because it silently merges genuine identical entries.

Data export

One tool, export_all_data, is the only way out. It writes a ZIP — meals.csv, water.csv, weight.csv, body_measurements.csv, goals.csv, goals_history.csv, profile.csv, account.csv, telemetry.csv, connections.csv, health_sync.csv and a README.txt (order: EXPORT_ARCHIVE_FILES) — to exports/<userId>/nutrition-mcp-export.zip and returns a 60-minute signed link. A meals-only export_meals used to sit beside it and was removed rather than kept: two overlapping export tools made "export my data" ambiguous for the model, and the meal history is meals.csv inside the archive. The fixed per-user path means each export overwrites the last, and sweepStaleExports ages files out on the same horizon as the link, so nothing outlives its URL by more than one sweep.

src/zip.ts is a hand-rolled store-only (method 0) ZIP writer — Bun has gzip and zstd but no archive builder, and nine small CSVs do not justify a dependency. Two things in it are load-bearing: every size and offset is a byte length from TextEncoder (a multi-byte character in a meal description otherwise desyncs every following offset), and the DOS date/time is read in UTC, or the same Date emits different bytes on different machines and the determinism the tests rest on evaporates.

Invariants worth keeping:

  • The archive is everything the service stores about the user — the privacy policy says so in 9 locales, and its README's "Not in this archive" section lists the only exceptions (one-way hashes of the password, tokens and codes; dedupe keys and PKCE challenges; the runtime log; providers' logs and backups). A new per-user table or column goes into the export or into that list, and the policy's "Access and portability" bullet, together. account.csv comes from auth.admin.getUserById; connections.csv never selects a token or code column, and carries the Apple Health sync link as one extra row of kind health_sync (created, last used, last synced, expiry, fields, start date, phone timezone — never its token hash). health_sync.csv is the 8-day sent-values ledger, one row per day rendered in that day's own timezone (the zone it was counted in when sent, which can differ from the account's). Text a third party chose (OAuth client_name/redirect_uri, the MCP client name and session id) goes through csvThirdParty, which defuses spreadsheet formulas; the user's own logs do not, so meals.csv stays byte-identical.
  • Every CSV pairs each timestamp with a timezone column naming the zone it is rendered in, exactly as the meal export always has. An offset-less wall clock with nothing beside it silently re-resolves against whatever timezone the account has later — that was #97.
  • Every builder emits its header even with zero rows, and goals.csv / profile.csv are header-only when the record is null (goals_history.csv is header-only when there is no history). A file that vanishes when a table is empty makes the archive shape unpredictable for anything reading it.
  • meals.csv is byte-identical to buildMealsCsv, whose headers are the importer's column aliases. It is the only file with a way back in; renaming a column there for looks breaks a re-import silently.
  • Alcohol is not gated on alcohol_tracking_enabled. The opt-in governs display, not the export — the privacy page promises the export always includes what was logged. It looks like a missing check, so the code says why.
  • exportAllData derives tz and weight unit from one getProfile row. The getUserTimezone / getPreferredWeightUnit wrappers are each their own select * from profiles, so chaining them multiplies one query by the number of preferences read.
  • getAllMeals / getAllWater / getAllWeight / getAllBodyMeasurements (on selectAllForUser) reconcile against an exact count and throw when short. PostgREST caps rows at 1000 by default, which truncated an export once already (#66); a loud failure beats a quiet partial backup. The window readers below reconcile the same way.

Reads and error text

  • Every logged_at window read goes through selectLoggedWindow (src/supabase.ts). getMealsInRange / getWaterInRange / getWeightInRange / getBodyMeasurementsInRange page with .range(), order by logged_at then id, drop the adjacent duplicate a backdated insert between pages can produce, and reconcile the deduped length against the first page's exact count, throwing result would be truncated (category read_truncated) when short. The three get*ByDate readers delegate to them. The id tie-break is load-bearing: date-only imports all anchor at local noon, so ties at a page edge are routine. An unpaged select kept PostgREST's oldest 1000 rows, so a 365-day get_trends showed the latest 30 days as zeros. The range caps (MEALS_RANGE_MAX_DAYS 31, SUMMARY_RANGE_MAX_DAYS 92, WEIGHT_RANGE_MAX_DAYS 366, BODY_MEASUREMENT_RANGE_MAX_DAYS 366) are about response size, not truncation. getBodyMeasurementsInRange takes an optional kind, applied in the database (selectLoggedWindow's filter), so the exact count covers the filtered set rather than the whole window.
  • Meal listings render through renderMealListing (src/meal-listing.ts). get_meals_today, get_meals_by_date and get_meals_by_date_range take detail: "compact" | "full", default "compact": one line per meal — local HH:MM, type, description (clipped at 200 characters), calories and non-null nutrients (alcohol gated exactly like formatMeal, since the opt-in exists for users in recovery), a notes flag in place of the note text, and [id: …], which update_meal/delete_meal need. "full" is the old per-field block, including notes, and never clips. Both name the profile timezone once (Times are local (…).) and print local time by slicing formatLocalDateTime — never a raw UTC ISO string, which filed a Kyiv user's 21:00 dinner at 19:00Z. Output is capped at MEAL_LISTING_MAX_CHARS (40_000): whole days are added while they fit, a meal boundary is only the fallback when the first day alone overflows (at least one meal is always shown), and a truncated listing ends with a notice naming the concrete continuation call. The module is pure — it must never import mcp.ts or Supabase. Water and weight listings get local time and the timezone header too, but no detail param and no budget (weight is at most 366 short lines). Body-measurement listings (get_body_measurements) get local time, the timezone header and the MEAL_LISTING_MAX_CHARS whole-day budget: the first day is always shown, and a truncated listing names the date to continue from. get_nutrition_summary's structuredContent.meals is not every meal: topMealBreakdown sends the order-preserving union of each metric's top MEAL_BREAKDOWN_TOP_N (at most 64 rows; added sugar deliberately does not rank rows, so structuredContent.meals is unchanged with or without _meta — its list draws from the kept rows that carry a value plus _meta's extra, see below) — fewer rows, so it still validates under the unchanged schema. The per-metric count of meals with a value above zero travels in the result's _meta under MEAL_CONTRIBUTORS_META_KEY ("nutrition-mcp.com/meal-contributors"), on both return paths, and the widget's "N more meals" line is contributors − shown. It is not a structuredContent field because output schemas are frozen (see "Server wiring" above): shipping it there as meal_contributors failed every summary call on dev for hosts still holding the old tool list. shared/bridge.js hands the result's _meta to render as its second argument. A host that drops it leaves the new widget on hedged wording rather than a number it cannot know: "+ N or more" past 8 rows, "+ possibly more" at exactly 8 (the commonest trim, where one set of big meals leads every metric), and an exact count only when sum(days[].meal_count) shows the server trimmed nothing. One known transitional miscount remains: a host still running the pre-change widget HTML from its cache (the ui:// URI is unchanged) computes rows − 8 against the now-bounded meals and undercounts "N more" until it refetches the resource — the payload still validates, only that line is low. The summary widget repeats MEAL_CONTRIBUTORS_META_KEY as a literal (it cannot import), so src/mcp.test.ts asserts the assembled widget contains it; the harness imports it from src/widgets.ts, where it is defined. MEAL_BREAKDOWN_TOP_N (defined in src/widgets.ts so the harness can import it, re-exported from mcp.ts) must equal CAP and the extra cap in public/widgets/src/shared/macros.js; public/widgets/macros.test.ts checks both, since a mismatch makes the widget's list and its "more" count disagree. Added sugar never enters structuredContent (the schemas are frozen): log_meal, update_meal, get_goal_progress, get_nutrition_summary and get_trends carry it in _meta under ADDED_SUGAR_META_KEY ("nutrition-mcp.com/added-sugar", src/widgets.ts), built by buildAddedSugarMeta (src/added-sugar.ts) as { v: 1, goal, days, meals, contributors?, extra? }. extra is get_nutrition_summary's alone (the single-day tools list every meal of the day, get_trends has no list): addedSugarExtra ranks every meal in the range by added sugar (one decimal, > 0, ties to the earlier meal — topMealBreakdown's rule), takes the top MEAL_BREAKDOWN_TOP_N and sends those not among the kept rows, as { description, meal_type, date, added_sugar_g } built from mealBreakdown's own row. Without it a 30 g sweetened drink that tops no other metric was missing from the added-sugar list while contributors counted it. The widget validates extra as untrusted (an array; each entry rebuilt from those four fields, kept only with a string description and a finite positive added_sugar_g; at most 8), drops it entirely when the position join of meals fails, and adds the rest to the added-sugar cell's list only (metricRows), so every other metric's list and count is untouched, "+N more" stays contributors − shown, and with no extra it renders exactly as before. Optional and additive, so v stays 1. days is null for a day with no recorded value (never 0), and meals (keyed by meal id) is built from exactly the meals behind the rows the tool returns, in row order, because the rows carry no id and withAddedSugar in shared/macros.js matches them by position (and only when the counts agree). Without the payload the strip is byte-for-byte the four-limit one. Every template repeats the key as a literal, asserted by src/mcp.test.ts and public/widgets/macros.test.ts.
  • A set added-sugar limit with nothing recorded is stated, never dropped. addedSugarNotRecorded (src/insights.ts) is the one wording — not recorded on this day (limit 29g) in formatProgress (log_meal, update_meal, get_goal_progress, each summary day), not recorded in this period (limit 29g) in the summary's average line, computeTrends and computeWeeklyDigest — gated on an active ceiling (0 included). Dropping the line let a model read total sugar against the added-sugar limit (a cola logged with sugar_g 35 and no added_sugar_g). Without a limit the output is unchanged, and partial coverage keeps the days-with-data notes. Every AddedSugarMeta carries goal on every return path, so the widgets can show the same gap.
  • sugar_g without added_sugar_g is refused once ADDED_SUGAR_REQUIRED_FROM has passed. log_meal refuses any call giving sugar_g (0 included) with no added_sugar_g; update_meal only when it gives sugar_g without added_sugar_g and the stored meal's added_sugar_g is null. Checked before any write (for update_meal, after the stored-sugar read), as a ToolError carrying its own analytics category, added_sugar_missing (addedSugarMissingError in src/added-sugar.ts; ToolError's optional category beats categorizeError's wording tiers). bulk_import_meals and the import widget never apply it — third-party exports rarely carry added sugar. The env var is an ISO-8601 date or offset date-time, read per call by addedSugarRequiredNow() in src/mcp.ts (tests set and restore process.env, no mock.module); unset, empty or unparseable is off, and a bad value logs one [config] warning at startup. The gate exists because hosts cache tools/list for days: a client still on a list from before added_sugar_g cannot send the field, so enforcing early fails every sugared meal those users log, each an isError result against the directory health badge — set it well after the deploy that advertised the field. The field descriptions and NUTRIENT_COVERAGE say a call "may be refused", which is true with the gate on or off.
  • ToolError (src/errors.ts) is the only error text that reaches the model. withAnalytics returns a ToolError's message verbatim; every other error becomes a per-category message (userFacingError in src/analytics.ts) plus an 8-hex ref from newErrorRef(), and the raw message is logged JSON-escaped under that ref with no user id. The weekly-summary resource, the import's per-row insert_failed and lookup_barcode's Open Food Facts fallback follow the same rule outside withAnalytics. Throw ToolError only for text written for the caller, never to wrap third-party text. csv.ts / chunk.ts are @inlinets-inlined into widgets and must not import it.
  • Body measurements (body_measurement_log, 20261002120000_body_measurements.sql; tools log_body_measurement, get_body_measurements, update_body_measurement, delete_body_measurement, set_length_unit). A row stores the canonical integer value_mm plus value_entered and entered_unit exactly as typed, so a display in the entry's own unit shows the user's number back rather than a round-tripped one. The write unit is the explicit unit, then the saved profiles.preferred_length_unit (nullable, no default), then a refusal (pickLengthWriteUnit in src/units.ts); the weight unit is never consulted. update_body_measurement defaults to the unit the entry was recorded in. PLAUSIBLE_LENGTH_MM is a set of per-site typo guards (mm typed as cm, an extra digit, a cm/in swap at the extremes) whose refusal adds an other-unit hint only when the same number would be plausible in the other unit — not health bands, and it cannot catch a cm/in swap inside the overlap (upper_arm 12–39.4 is valid in both). BODY_MEASUREMENT_KINDS must equal the migration's body_measurement_log_kind_check list (pinned by src/units.test.ts); adding a kind needs a migration that drops and re-adds that constraint. One value per site: there is no side column, a left/right goes in notes. bodyMeasurementIdempotencyKey hashes kind (so waist 80 cm and hips 80 cm at the same instant stay two rows) and value_mm (so 80 cm and 31.5 in are one), and its field list is positional, so it is frozen once shipped; notes are decoded before hashing, unlike weight and water (#79). The landing-page stats deliberately exclude measurements. The tools declare no outputSchema (null entries in src/output-schemas.frozen.json).

OAuth

src/oauth.ts is the authorization server every MCP client signs in through, and it is the one place in this repo where a mistake hands out someone else's account: until #148, POST /register gave every caller the same static client, /authorize accepted any redirect_uri and PKCE was optional, so an attacker could craft an authorize link pointing at their own redirect, let the victim sign in on the real login page, and redeem the code for a year-long read/write token.

  • Every client registers its own credentials (RFC 7591), stored in oauth_clients. /register validates the metadata (a bad body is a 400 invalid_client_metadata, not a 500), mints a fresh client_id, stores a confidential client's secret only as a sha256 hash, and never returns the env client again. Open registration alone would not have fixed #148 — an attacker can register their own redirect — which is why the consent notice below is the second half of the fix.
  • The legacy env client (OAUTH_CLIENT_ID/OAUTH_CLIENT_SECRET) survives only until its sunset. Both vars are optional now: without them there is simply no legacy client, and the router no longer throws. With them, the client is resolved in memory (never looked up in oauth_clients) and accepted at /authorize only with a loopback redirect or one listed in oauth_legacy_redirect_uris — a frozen snapshot of the redirects in the old registered_clients table (dropped in 20260929120000_drop_registered_clients.sql) that Anton reviewed by hand, because anyone could have written those rows. The snapshot holds per-user and per-connector ids, so it is inserted directly into the database and never committed. Every legacy authorize logs [oauth] legacy-client authorize origin=<origin>; that line is what measures whether the client can be retired (planned for about 90 days after this landed).
  • One built-in first-party client: HEALTH_SYNC_CLIENT (src/oauth-store.ts, id nutrition-mcp-health-sync). The Apple Health sync pairing signs in through the ordinary /authorize as this server's own client (see "Apple Health sync"). withFirstPartyClients(withLegacyClient(store, legacy)) resolves it in memory like the legacy env client: never a row in oauth_clients, so the client sweep can't remove it, and touchClient is a no-op. It is public (none), and its only redirect is this server's own healthSyncCallbackUrl(getBaseUrl(c)), byte for byte — redirectAllowed takes the request for that; anything else is the usual JSON 400 with no Location. renderClientNotice shows LOGIN_CLIENT_NOTICE.healthSync (warning tint, no host) only for this client id — a registered client with the same callback path never gets it, and client_name is still never rendered. /token refuses it with 401 invalid_client before any code is spent: /health-sync/callback redeems its codes straight from the store (consumeAuthCode, then client id, exact redirect_uri, verifierMatchesChallenge from src/oauth-validate.ts), so no access or refresh token can ever be minted for it.
  • Redirect rules (src/oauth-validate.ts, applied at both /register and /authorize). https: with any host, no fragment and no userinfo; http: only for localhost, 127.0.0.1 or [::1]; a private-use custom scheme (cursor://…) unless it is on the denylist javascript, data, file, vbscript, blob, about, ftp, ws, wss, http, https; 2000 characters at most. Matching is exact string equality, with one exception: loopback matches scheme, host, path and query but ignores the port, because Claude Code and other native clients bind a random port per run. localhost and 127.0.0.1 are not interchangeable — a client registered with one does not match the other. KNOWN_CLIENT_HOSTS (claude.ai, claude.com, chatgpt.com) lives in the same file.
  • PKCE is mandatory, S256 only. code_challenge must be 43 base64url characters; plain or any other method is rejected. An absent code_challenge_method is treated as S256 and logged as [oauth] pkce-method-absent client=<id>, since the spec default would otherwise be plain.
  • Validation happens at /authorize, before the page renders — never at /approve. An unknown client or an unregistered redirect gets a JSON 400 with no Location header: redirecting would deliver the error to the very URI we just refused to trust. Only after the client and redirect check out do errors (a bad response_type, a missing state, a missing or bad challenge, a bad resource) redirect back with error and state, built with new URL(redirectUri) + searchParams so custom schemes work.
  • The consent notice shows where the user is being sent. The spec requires the login page to display the redirect host: a known host gets a plain "you'll be sent back to {host}", any other https host and any custom scheme get a warning, and loopback gets its own warning. client_name is never rendered — it is whatever the registrant typed, and a client registered as Claude would otherwise vouch for itself. See the login.html paragraph under "Public site" for how the notice reaches the page.
  • A sign-in session is bound to the browser that started it. /authorize sets a binding cookie for that session — named nm_oauth_bind_<16 hex of sha256(session id)>, __Host--prefixed over https and bare on plain-http local dev, which cannot hold a Secure cookie — holding 32 random bytes, and stores their sha256 on the session; /approve, POST /authorize/google and /auth/google/callback refuse a request whose cookie does not hash to it, with a 400 session_mismatch and one [oauth] session-binding-mismatch route=<route> line, leaving the session untouched. Why: the session id is in the login page's HTML, so whoever fetched /authorize holds it, and with open registration that can be an attacker's server. It opened a session for its own client, started the Google leg with the scraped id and handed the victim only Google's genuine account chooser — the callback then finished the attacker's session in the victim's browser and sent the code to the attacker's redirect, and the consent notice was never on screen. It is SameSite=Lax, not Strict, because Google's redirect back to the callback is a cross-site top-level GET, and Strict drops the cookie on exactly that request. One cookie per session, not one per browser: a shared per-browser value had to be minted by whichever /authorize arrived without one, so two first-time loads in flight together (a double-clicked Connect) each minted their own under the same name, the browser kept the last Set-Cookie, and the other tab's sign-in failed the check. Per-session names can't overwrite each other, and parallel sign-ins and the language switcher (which mints a fresh session) each get their own. Max-Age is the session's 10-minute TTL, a finished sign-in deletes its cookie, and /authorize clears them all once a request carries 10, so a page bouncing a browser through /authorize can't grow its Cookie header without bound. /authorize/google is a POST from a form on the login page — a GET answers 405 — so the Google leg always starts from the page carrying the notice. The cookie is read nowhere else: /mcp stays Bearer-only. The site CSP has no form-action, and it must not gain 'self' alone: form-action also governs the redirect after a submit, which is Google for one form and the client's redirect for the other; src/index.test.ts pins that.
  • authorizeUrl() is the only place a session turns back into a URL, for the language switcher, and it must serialize every parameter /authorize requires — code_challenge_method and resource included. A dropped one does not fail loudly: the switcher link re-enters /authorize and the flow breaks there.
  • Logs carry redirect origins only. Every [oauth] … rejection logs one line with the client id and the redirect origin — never a full redirect URI (they carry per-user ids), never a token, code or secret, never a user id.
  • /token authenticates the client (authenticateClient) before touching a code or refresh token. Credentials come from the form body (client_id, plus client_secret for client_secret_post) or Authorization: Basic, whose two halves are form-decoded per RFC 6749 §2.3.1 — but the raw halves are accepted too, because the MCP SDK sends btoa(id:secret) unencoded and moves pre-registration clients to Basic on its own, so a legacy secret with a + or % would otherwise stop matching; a secret in both places is 400 invalid_request, and a body client_id beside Basic must name the same client. An unknown client, a confidential client without its secret, a wrong secret, or a public client presenting one is 401 invalid_client, with WWW-Authenticate: Basic when Basic was tried. Secrets compare as sha256 hashes with timingSafeEqual. The registered token_endpoint_auth_method decides only secret-or-no-secret, not the transport: a client_secret_basic client may post its secret and vice versa, because the MCP TS SDK picks the transport from our advertised methods rather than its registration, and possession of the secret over TLS is the same proof either way. The legacy env client's secret is optional but must match if sent, and until its sunset a body client_secret with no client_id is taken as the legacy client (as the pre-registration /token did); with no legacy client configured that is 401 invalid_client. The body-limit 413 and shutdown 503 in src/index.ts answer /token before the router does, so an app-level /token middleware adds Cache-Control: no-store / Pragma: no-cache to those too. A successful authentication stamps oauth_clients.last_used_at fire-and-forget (store.touchClient), never the legacy client.
  • authorization_code grant. code missing is invalid_request. Client authentication runs before the code is consumed, so an unauthenticated caller (401 invalid_client) can't burn a code; every check after that spends it. These are 400 invalid_grant: a code issued to another client (a null client_id code skips this), a redirect_uri that is missing or not byte-identical to the one /authorize got (no loopback port leniency here), and a code_verifier that is missing, not 43–128 [A-Za-z0-9._~-], or whose pkceS256 doesn't match — a missing verifier is deliberately invalid_grant, not invalid_request, so it is indistinguishable from a wrong one. A code with no challenge is always refused. A resource sent here must be this server and, when the code carries one, normalize to the same value, or 400 invalid_target; omitting it is fine.
  • Refresh tokens are bound to their client (refresh_tokens.client_id). Client credentials are optional on a refresh, but if sent they must authenticate (a confidential client must prove its secret), and a token with a non-null client_id is invalid_grant for any other caller — including one that sent no client at all; the mismatched token stays consumed. Null-client tokens, written before the column existed, are accepted from anyone so nobody connected earlier is logged out, and their rotated successor is bound to whichever client identified itself. The rotated refresh token always comes back in the same response. Missing refresh_token is invalid_request; a client-authentication failure is 401 invalid_client (checked before the token is consumed, so it doesn't burn it); every other refresh failure is invalid_grant. Apply 20260926120000_oauth_refresh_client.sql to an environment's database before the code reaches the branch that environment deploys from (dev before dev, production before main): consumeRefreshToken selects client_id, so without the column every refresh is invalid_grant and every client is logged out, and storeRefreshToken's insert 500s the authorization_code grant after the code is spent.
  • Every /token response sends Cache-Control: no-store and Pragma: no-cache — errors and the rate limiter's 429 included, which is why that middleware is registered ahead of rateLimitAuth.
  • iss (RFC 9207) is on every authorization response: the success redirect from finishAuthorization and every post-validation error redirect from /authorize. It comes from issuerFor() in src/discovery.ts, the same helper that builds the metadata issuer, because clients compare the two byte for byte; the metadata advertises authorization_response_iss_parameter_supported: true and token_endpoint_auth_methods_supported: ["none", "client_secret_post", "client_secret_basic"]. No CIMD flag — client ID metadata documents are not supported.
  • Access tokens, refresh tokens and auth codes are hashed at rest. Every token and code is minted by newOpaqueToken() (32 random bytes, base64url) and only hashSecret(raw) — lowercase sha256 hex, src/token-hash.ts, the same function client secrets use — is written to the existing token / code column. The store owns the at-rest form: OAuthStore and getUserIdByToken take raw values, and the supabase.ts functions behind them hash on write and match .eq(column, hashSecret(raw)) on read, so neither a raw value nor a stored hash presented as the token matches anything. Consumes stay atomic single-use delete … returning. Rows written before hashing (raw UUIDs) were rewritten by supabase/migrations/20260927120000_hash_oauth_secrets.sql using encode(sha256(convert_to(x,'UTF8')),'hex'), which must equal hashSecret byte for byte (src/token-hash.test.ts pins the shared abc vector) — dev and production were both backfilled on 2026-09-27, after the hashing code (which also read raw rows) was live, and only then was that raw-lookup fallback removed. Any environment still holding raw rows must run that migration before this code reaches it, or those users are logged out. src/oauth.test.ts's fake store keeps the same contract, but it re-implements it, so it proves nothing about supabase.ts: src/oauth-supabase-store.test.ts calls the real store functions against a stubbed global fetch (supabase-js resolves it per call; no mock.module) and asserts the written row is hashSecret(raw), the lookup filters on that hash alone, and a raw-UUID row no longer resolves.
  • Lifetimes. ACCESS_TOKEN_TTL_SECONDS (24h, was 365 days) drives both the stored expires_at and expires_in; REFRESH_TOKEN_TTL_SECONDS (90 days) is passed to storeRefreshToken and counted from each rotation (sliding), each token strictly single-use. Rows written before keep their expiry — nothing rewrites expires_at.
  • One /token log line per call: [oauth] token grant=<authorization_code|refresh_token|missing|unsupported|unknown> result=<ok|OAuth error code|rate_limited|server_error> client=<id|legacy|none>[ reason=<…>]. It is written by the /token middleware from a per-request note the handler fills in (TokenCallNote), and result is read off the response itself, so every early return, the limiter's 429 (grant=unknown) and a thrown error all log exactly once; the handler no longer logs token-rejected lines of its own. The app's body-limit 413 and shutdown 503 answer before the router, so the app-level /token middleware in src/index.ts logs those (grant=unknown result=payload_too_large|shutting_down client=none) via logTokenCallAnsweredBeforeRouter, which skips any call the router already noted. grant is a fixed vocabulary, never the caller's text, and no token, code, secret or user id ever appears.
  • Sign-up is an explicit action, never a fallback. The login form's email section has two submit buttons posting to /approve, action=signin and action=signup; a missing or unknown value (old cached pages post login) is signin. Until brief 11, any failed sign-in silently created an account with the typed email and password, so a mistyped password became a sign-up attempt whose raw Supabase "User already registered" both confused the user and confirmed the address had an account. signInUser / signUpUser now throw SignInError / SignUpError (src/auth-errors.ts) carrying only a stable code mapped from GoTrue's error_code — never the message, which can quote the address — and /approve renders only translated LOGIN_ERRORS picked by that code. On signin, invalid_credentials is invalidCredentials and any other failure (a 429, an outage) is signInFailed; signUp is never called. signup tries a sign-in with the same credentials first, so the right password for an existing account just connects, and only invalid_credentials goes on to auth.signUp; user_exists (GoTrue's user_already_exists with Confirm email off: the address has an account and the password was wrong) then reads as invalidCredentials, weak_password → weakPassword, email_invalid (email_address_invalid) → emailInvalid, rate_limited → signInFailed, anything else → signUpFailed. GoTrue's validation_failed is deliberately other: it covers both a malformed email and a password over bcrypt's 72 bytes, so /approve refuses a password over MAX_PASSWORD_BYTES (72, counted in UTF-8 bytes) with passwordTooLong before calling sign-up, and never guesses the field from that code. Confirm email stays off for now (no custom SMTP yet), and because this change has no confirmation flow, signUpUser refuses a sign-up that comes back without a session (i.e. held for confirmation) and logs [auth] sign-up-unconfirmed, rather than return a user id for an address nobody has proved they own — so switching Confirm email on without the confirmation flow breaks sign-up loudly instead of issuing codes for unconfirmed accounts. What remains open without confirmation: anyone can register an address they don't own (the pre-account-takeover risk — Supabase later links a Google sign-in for that address into the same account), and Create account still reveals whether an address is registered (wrong password vs account created). The full confirmation flow (confirm page that sets the password, reset, enumeration guards) is parked in .git/brief11-full-email-confirmation.patch locally, pending custom SMTP.
  • HSTS on every https response, never on plain http. The security-headers middleware in src/index.ts sets Strict-Transport-Security: max-age=31536000; includeSubDomains only when isHttpsRequest (src/url.ts) says the request arrived over https — x-forwarded-proto read the way getBaseUrl reads it, falling back to the URL's scheme — so http://localhost dev is never pinned. No preload: it is a one-way door that needs every subdomain on https for good, and is Anton's call after a month without problems. If Cloudflare's dashboard HSTS is ever switched on as well, the two headers must agree; prefer the app header. src/index.test.ts pins both cases.
  • Supabase Auth sessions are ended the moment they are created. GoTrue has no verify-only call, so signInUser / signInWithGoogleIdToken / signUpUser (src/supabase.ts) each mint an auth.sessions row that nothing uses and that, by default, never expires. discardAuthSession calls auth.admin.signOut(access_token, "local") on the same throw-away client right after — fire-and-forget, logging only [auth] session-revoke-failed status=<n> — which makes GoTrue delete that session and cascade its refresh tokens. The privacy policy says so. The Auth session time-box stops a missed session from being used; it does not delete the row — auth.sessions rows left by a missed revoke are removed only by an explicit purge (one was run on 2026-09-29, deleting every session older than an hour). Covered by src/auth-session.test.ts against a stubbed fetch.
  • startOAuthCleanup() (src/oauth-cleanup.ts) sweeps once at boot and then hourly (every deploy restarts the interval, and the privacy policy promises expired rows are gone within an hour), started only in src/index.ts's import.meta.main block, never on import, with the same re-entrancy guard as startExportCleanup(). It deletes expired rows from oauth_tokens, refresh_tokens and auth_codes first, then oauth_clients rows with last_used_at is null created over 7 days ago but not before CLIENT_SWEEP_FLOOR_ISO (2026-09-26 14:00Z, past the later Phase B deploy). That floor is the real protection for clients registered between the A and B deploys: Phase A never stamped last_used_at, and their refresh tokens predate refresh_tokens.client_id, so they carry client_id NULL and no client_id in (…) query can see them — yet deleting such a client makes its next refresh 401 invalid_client (the SDK sends client_id, and authenticateClient fails before the null-client leniency runs), i.e. a logout. Those tokens were minted for 365 days and rotate to null-client successors when refreshed without credentials, so the floor stays until refresh_tokens has no null client_id left. Inside the window, a client still named by a refresh_tokens or auth_codes row is kept too — that covers an authorization in flight and a failed fire-and-forget touchClient, not the pre-B case; the check reconciles against an exact count and throws (skipping client deletion that run) if PostgREST's row cap truncated it. Candidates are paged by client_id (so a page of kept clients can't stall it), the delete re-checks last_used_at is null and the window in the same statement, and it logs counts only. The queries are in supabase.ts; sweepOAuth(store, now) takes an injectable OAuthCleanupStore for src/oauth-cleanup.test.ts. The same tick then runs sweepHealthSync (see "Apple Health sync"), independently: a failed OAuth sweep does not skip it, and it logs its own [health-sync] cleanup … count line.
  • src/oauth.test.ts never uses mock.module. createOAuthRouter(deps?) takes an injectable store (OAuthStore, src/oauth-store.ts), auth and now, defaulting to Supabase; the tests pass in-memory fakes. mock.module is process-wide (see the "/mcp over HTTP" note above for what that already broke), and injection keeps these tests independent of every other file's stubs. The one test that needs the env client sets and restores OAUTH_CLIENT_ID around createOAuthRouter(), which reads env at construction; no other test may rely on it, since Bun auto-loads the env file.

Apple Health sync

An optional iOS Shortcut writes daily totals of closed days into Apple Health on the user's own iPhone. Decisions Anton locked: a Shortcut only, never a native app; closed days only; upward top-ups, decreases only announced; pairing through a link opened on the phone itself, not an MCP tool — the tool count stays 41 and the only model-facing changes are one get_profile content line (healthSyncProfileLine in src/mcp.ts: connected date, sent through, last sync; content only, structuredContent untouched) and the delete_account description; an 8-day sent record that is exported; water opt-in at connect, alcohol never (HealthKit has only a drink count, and the opt-in exists for users in recovery), sugar not sent for now (still tracked in the MCP; sugar_g is not in HEALTH_SYNC_FIELDS, and a link created while it was keeps it in its stored fields harmlessly, because the routes filter them through isHealthSyncField), backfill 0–7 days, default 0. Whoop is out of scope and is never mentioned anywhere.

Files: src/health-sync.ts (pure: constants, field map, day totals, close instant, window, planPending, applyAck, body parsers; no Supabase, no Hono, never imports mcp.ts), src/health-sync-store.ts (HealthSyncStore; every secret goes in raw and is hashed inside, like the OAuth store), src/health-sync-routes.ts (createHealthSyncRouter(deps), mounted in src/index.ts; isHealthSyncPath lists its paths), src/copy/health-sync*.ts (the two Safari pages, 9 locales, plain text), supabase/migrations/20261003120000_health_sync.sql (health_sync_pending, health_sync_links, health_sync_days: RLS on with no policy, revoked from anon/authenticated, service_role only). The shortcut's build sheet and the phase-0 device checklist are docs/apple-health-shortcut.md; its name must stay exactly HEALTH_SYNC_SHORTCUT_NAME (Nutrition MCP Health), because the callback page runs it by name. Tests inject fakes (deps) or stub global fetch; never mock.module. Apply the migration to an environment's database before the code reaches the branch it deploys from — deleteAllUserData deletes from these tables first, so without them account deletion fails.

  • Pairing makes the server an OAuth client of itself, so the whole hardened sign-in (password, Google, browser-binding cookie, consent notice) is reused unchanged rather than re-implemented. POST /api/v1/health-sync/start (phone tz, include_water, backfill_days) stores a pending row — connect id and device secret as hashSecret, plus a server-generated PKCE verifier kept raw (the server must derive the challenge from it; it is single-use, cleared at callback, and dies with the row in 30 minutes) — and returns connect_url + device_secret. The shortcut saves the secret and opens the link in Safari; GET /health-sync/connect/:id redirects to /authorize with HEALTH_SYNC_CLIENT_ID, state = connect id and the S256 challenge (see the first-party client under "OAuth"); GET /health-sync/callback redeems the code from the store, mints a 10-minute claim code and serves a page that navigates to shortcuts://run-shortcut?name=…&input=text&text=<claim code> (no visible code); POST /claim atomically consumes the pending row matching both the claim code and the device secret, replaces the user's link and returns the nmhs_ token once, with site, which the shortcut compares to its hard-coded base URL.
  • Why a link that anyone can start is safe. The threat is #148's shape: an attacker starts a flow and gets the victim to finish sign-in. Here whoever called /start holds the device secret, but the claim code only ever reaches the browser that finished sign-in — the victim's own phone — and that phone never holds the attacker's device secret; /claim needs both. The consent notice tells anyone who did not just start this from the shortcut on their own iPhone to close the page. Failed claims cost an auth strike and are counted process-wide, but only as an alert=claim_failures_high on the log line, never as a refusal: a gate there could be filled from rotated x-forwarded-for values (getClientIp trusts a spoofable header) and would lock every real phone out of pairing. /start does keep a process-wide cap on top of rateLimitAuth (HEALTH_SYNC_START_GLOBAL_LIMIT in src/rate-limit.ts), as a deliberate trade-off: it bounds database writes, and a flood only delays new pairings, never syncs on existing links.
  • URLs handed to the phone use the configured site, never the request host. /start's connect_url and /claim's site come from configuredSite() — PUBLIC_BASE_URL when it is a bare http(s) origin, else the canonical SITE — because getBaseUrl trusts x-forwarded-host. Only the /authorize redirect and the callback URL follow the request's own origin, since /authorize checks the redirect against it. A deploy that is not nutrition-mcp.com (the dev app, localhost, a fork) must set PUBLIC_BASE_URL, or its phones are sent to production and get invalid_token.
  • The link token is nmhs_ + newOpaqueToken(), stored only as hashSecret, one per user (unique(user_id); a reconnect is one upsert, so the old token stops working in the same statement and a failed write leaves the old link rather than none). It expires 90 days after last use and 365 days after creation at the latest; last_used_at/expires_at are written at most hourly. Lookup is three-state like getUserIdByToken: unavailable is 503 with no strike, invalid is 401 invalid_token with WWW-Authenticate: Bearer realm="nutrition-mcp", error="invalid_token" (no resource_metadata) and a strike, and anything not nmhs_-shaped is refused before the database. Separate tables, so an OAuth access token never works here and an nmhs_ token never works at /mcp — authenticateBearer (src/middleware.ts) refuses the prefix with a 401 and a strike before any lookup — tested both ways. The shortcut keeps the token in its own stored content (Store / Get Stored Content, Global Value off), not in a file, and the Shortcuts app may sync it to the user's other devices through iCloud; the privacy policy, the terms and the /apple-health page say so. The build guide is docs/apple-health-shortcut.md.
  • Closed days only, and the close is zonedHourUtc(D+1, tz, 5) — 05:00 local the next morning, never day start plus hours (an hour off across DST). GET /pending offers [max(sync_start_date, lastClosed − 6), lastClosed], so a missed morning catches up and a gap longer than 7 days is never backfilled. Days are bucketed in the profile timezone, else the phone's zone from /start (fallback_tz, never written to profiles), else UTC, and the response says which (timezone_source). Totals are built in computeDayTotals, not the zero-filling sumMeals/totalsPayloadOf: a nutrient no meal carries is null and omitted from values, a real 0 is sent.
  • The ledger (health_sync_days) is what makes top-ups possible. Health can only add samples, so the server remembers what was acked per day and offers: an initial entry until one is acked; then a topup for a rise of at least 20 kcal / 2 g / 10 mg / 100 mL; for a fall of the same size only a notice (once per field per value, in notified), naming the Show All Data path and never "Delete All Data from Shortcuts"; no top-up but a notice for a suspect jump (more than 1.5× and more than 800 kcal) or after 9 top-ups; a frozen day, with one notice, once the timezone changed after it was sent; and a stuck notice pointing at Health → Sharing → Apps → Shortcuts once an entry was offered 3 times without an ack. Automation runs leave a stuck day alone; GET /pending?mode=manual (the shortcut's Sync now) sets retryStuck, which resets offer_count and clears notified.stuck, so fixing the permission and syncing by hand recovers it. Every entry has its own sample time (12:00:00, then 12:0n:00 for top-up n), which is what lets the shortcut's in-flight recovery find a sample it already logged. Notices are English phone-side text, not model-facing. Acks echo the entry and are idempotent on entry_id; the ledger records what the phone logged, not a recomputation. An ack applies only to a day inside ackWindow (the offering window plus the day that just dropped out of it at 05:00, never before sync_start_date) that already has a ledger row, so /ack never creates rows. The two routes write disjoint columns under guards: insertDays inserts only new rows, and updateDay writes only while the row still has the topup_seq / sent_values state the caller read — /pending writes only offer_count, notified and timezone and drops an entry whose write lost the race, /ack writes only the sent columns and counts a lost race as skipped. Rows are kept 8 days (HEALTH_SYNC_RETENTION_DAYS, one more than the window), survive a reconnect (so a re-paired phone does not resend days Health already has) and are deleted on revoke.
  • Fail closed. Meals and water come from getMealsInRange/getWaterInRange, which reconcile and throw read_truncated; any read failure is 503 unavailable with nothing computed and nothing written, and the lease released. A partial read would send a day too low, and too low can never be corrected downwards — only up, by a top-up that would then double-count once the read recovers.
  • Lease and envelope. /pending takes a 2-minute per-user lease (busy, 409, while one is held); an ack with done: true releases it only when it echoes the matching lease_until, so a late ack from an earlier run cannot free a newer run's lease. Any other method or path under /api/v1/health-sync answers in the envelope too: 405 with Allow for a known path, 404 otherwise. Every body has ok (a shortcut can't read the HTTP status); failures are { ok:false, error, message, ref? } with error from a fixed vocabulary and ref only on server_error/unavailable. Handlers catch everything, so nothing reaches app.onError; the shutdown 503 and body-limit 413 in src/index.ts answer in the same envelope (and log only the [req] line, not a [health-sync] one), the global CORS middleware is skipped for isHealthSyncPath (no Access-Control-* header is ever sent), and responses are Cache-Control: private, no-store. /pending, /ack and /revoke share a per-user bucket of 40 a minute (HEALTH_SYNC_LIMIT_PER_WINDOW).
  • Logs. Exactly one [health-sync] route=<start|connect|callback|claim|pending|ack|revoke|unknown> result=<code>[ entries=N notices=N][ alert=…] line per call, never a user id, token, code, hash, connect id or email; the hourly sweep logs counts only. The connect id is a path segment, so the [req] access line in src/index.ts logs the path through accessLogPath(), which rewrites it to /health-sync/connect/:id.
  • Retention and deletion. sweepHealthSync (src/oauth-cleanup.ts) runs on the hourly startOAuthCleanup tick: pending rows past expires_at (a claimed one past claim_expires_at), links past expires_at or 365 days old, and ledger rows older than 8 days. deleteAllUserData deletes links, days and claimed pending rows first (an unclaimed pending row has no user id and expires within 30 minutes). Nothing can ever be removed from Apple Health by the server; the terms and policy say so.
  • The copy restates the constants. The /apple-health setup guide (src/copy/apple-health*.ts, rendered by scripts/gen-apple-health.ts; its install button is HEALTH_SYNC_SHORTCUT_URL, read from the env var of that name by shortcutUrlFromEnv, which accepts only an https://www.icloud.com/shortcuts/… link; it is a build-time value, passed as a Dockerfile ARG like NOINDEX, so each deploy links the shortcut built for its own base URL and a fork that sets nothing shows "coming soon" instead of sending users to nutrition-mcp.com), the /tools troubleshooting entries health-sync-yesterday, health-sync-higher and health-sync-stopped (9 locales), the privacy policy (9 locales), the expired-link page (9 locales), docs/apple-health-shortcut.md and README's "Apple Health sync" section name 05:00, the 7-day window, the 8-day record, the 30-minute connect link and 90/365 days. src/site-copy.test.ts pins all but README against the constants in src/health-sync.ts, so changing one fails until every locale says so. The localized Health app labels in those entries (Browse, Show All Data, Sharing → Apps) are AI-translated like the rest of the site; the shortcut's own menu items (Sync now, Status, Disconnect) are English, because one shared shortcut serves every locale.

Public site (public/*.html)

One design system, soft, rounded and glassy: neutral blue-grey surfaces with a green accent, big radii (20–32px), a header of two floating glass pills, three blurred colour blobs drifting behind the top of each page (blobs(), emitted by nav()), and the in-chat widgets' nutrient palette (--cal --pro --car --fat --wat --fib --sug --caf). Type is Urbanist (500–800) for all text and Geist Mono for codes, counts and labels, from Google Fonts; Urbanist is Latin-only, so /uk adds Mulish after it (localeFontLinks() in scripts/site-partials.ts, chained in the html[lang] --font overrides) and /ja downloads nothing extra: its override falls through to system Japanese fonts (Hiragino, Yu Gothic, Meiryo, Noto CJK) — M PLUS 2 was dropped as ~1 MB per page. The CSP already allows Google Fonts.

  • public/styles.css holds only what every page shares, in numbered sections: tokens on body (every dark value is declared once in the prefers-color-scheme block and once in body[data-theme="dark"], so a new colour must be added to all three blocks), keyframes, base + reveals, blobs, header, sheet menu, footer, consent banner, and the .nm-* primitives pages are built from (.nm-container, .nm-card, .nm-btn-*, .nm-chip, .nm-faq-row, …). Nothing in it is scoped to a single page: page layout goes in that page's generator as an inline <style> (the landing page's in scripts/landing-css.ts) built from the tokens and primitives — never a hardcoded light-only colour. The pre-redesign "Nutrition Facts" stylesheet and its token aliases (--rule, --accent, --surface, …) are gone; do not reintroduce them.
  • public/site.js (served at /site.js, loaded with defer by every page) owns the three-state theme control (every [data-theme-set] button, synced via aria-pressed, plus <meta name="theme-color">), the analytics consent banner and "Cookie settings" reopen (a no-op when window.nmConsent is absent, as on login and NOINDEX builds), the mobile sheet menu (focus trap, Escape, inert on everything outside, scroll lock, auto-close once the hamburger is hidden), the nav fit check (html.nav-tight hands the page to the hamburger whenever translated labels overflow the nav pill) and its sliding active indicator, same-page scroll-spy, the language <details> light-dismiss, [data-reveal] / [data-reveal="stagger"] entrance reveals, the .copy-mini buttons, the live-stats nav badge and the [data-gh-stars] counts. Reveals only hide content once html.js is set, so the pages are complete without script. Every effect is off under prefers-reduced-motion.
  • The header + menu markup is shared, not hand-copied: scripts/site-partials.ts exports nav(locale, suffix, currentSuffix?) and footer(locale, currentSuffix?), used by every generator — scripts/gen-index.ts, scripts/gen-tools.ts, scripts/gen-legal.ts, scripts/gen-alternatives.ts, scripts/gen-apple-health.ts, and scripts/gen-login.ts. Every public page is generator-driven now (the landing page and /tools were the last two hand-authored files; both moved onto gen-index.ts/gen-tools.ts) — public/login.html is the one page that's a genuinely different case, since its generated output is a runtime template rather than a finished page (see below). When the nav changes, change site-partials.ts and re-run every scripts/gen-*.ts — see the shared-chrome-data note under "Generators" below for why a generator whose own data file didn't change still needs re-running.
  • Analytics tags live in scripts/site-partials.ts, not in any generator, and nothing loads before consent. HEAD_ASSETS is STYLE_ASSETS (fonts, icons, styles) plus analyticsHead() when ANALYTICS_ENABLED: one inline <script data-analytics> that sets basic Consent Mode v2 defaults (all four signals denied) and exposes window.nmConsent.load(), which alone injects gtag.js (GA_MEASUREMENT_ID, Google signals off, cookie_expires matching the choice) and Microsoft Clarity (CLARITY_PROJECT_ID, then consentv2); only analytics_storage is ever granted, the ad_* signals stay denied. The choice is {v:1, choice, at} in localStorage consent, valid for CONSENT_MAX_AGE_DAYS (182, ~6 months); with nothing valid stored, a Global Privacy Control signal counts as denied. The consent banner is a strip nav() renders in the normal flow between the skip link and the sticky header — it pushes the page down rather than covering it, and since data-consent is stamped in <head> before first paint nothing shifts; reopened from the "Cookie settings" button footer() renders, it docks to the bottom edge (html[data-consent-reopen]). The logic — clicks, withdrawal (consent update, clarity("consent", false), reload) and deleting _ga/_ga_*/_clck/_clsk on any denial — is in public/site.js. Login has no analytics at all: gen-login.ts takes the analytics-free BASE_HEAD_ASSETS and passes { consent: false } to both nav() and footer(). NOINDEX (ANALYTICS_ENABLED false) drops the snippet, banner and button together. scripts/depersonalize.ts (which must leave none of the maintainer's personal info — name, email, GitHub/Patreon/Medium/YouTube links — on any page, in any locale; its closing guard exits 1 on residue under public/) strips all three by their data-analytics / consent markup and requires each on every page but login, so a ⚠ 0× means the markup changed. A new tracker must be injected inside load(), never as a static tag, and adding or removing one still touches the CSP in src/index.ts (Clarity needs https://*.clarity.ms in script-src/connect-src/img-src and https://c.bing.com in the last two), the privacy policy and terms in all nine src/copy/legal*.ts locales, and scripts/depersonalize.ts.
  • GitHub star counts are fetched server-side only. GET /api/github-stars (src/github-stars.ts) calls the GitHub API with no visitor data, caches a good count for an hour and a failure for 5 minutes (GitHub allows 60 unauthenticated calls an hour), and public/site.js fills every [data-gh-stars] badge from it, revealing a badge only once a number arrives. No visitor request reaches GitHub, so api.github.com is not in the CSP and the privacy policy (all 9 locales) says so; every GitHub button shows the count except the header nav icon.
  • Keep the pre-paint <script> right after <body> that applies the saved theme from localStorage — it is what prevents the light flash on dark-mode visitors.
  • Every request passes through Cloudflare, DigitalOcean's managed instance in front of the app, with no dashboard of our own. Its Email Obfuscation is on and cannot be switched off: it rewrites every mailto: and bare address in served HTML to a script-only /cdn-cgi/l/email-protection#… link. So every generator wraps its whole <body> contents in one <!--email_off--> … <!--/email_off--> pair — EMAIL_OFF_OPEN just before THEME_PREPAINT, EMAIL_OFF_CLOSE just after SITE_SCRIPT (scripts/site-partials.ts) — and src/alt-pages.test.ts pins exactly one pair per generated page with every address inside it. A new generator or a second <body> template needs both. depersonalize.ts leaves the comments in place.
  • The landing page's world map is k-anonymous: a timezone is named only once at least TZ_MIN_PROFILES (3) profiles use it — the privacy policy promises it. public_landing_stats() filters timezone_list / timezone_counts with having count(*) >= 3 (20260929130000_landing_stats_k_anonymity.sql), and publicLandingStats() in src/supabase.ts applies the threshold again, so either side deploying first is safe; with no counts it serves an empty list, never an unfiltered one. Exact counts never leave the process (timezoneLevels() buckets them, as shares of the published timezones only). The single timezones number still counts every distinct timezone — it names none.

Internationalization (i18n)

The site is being translated into German, Spanish, French, Dutch, Polish, Italian, Ukrainian and Japanese (LOCALES in src/routes.ts) — deliberately not Russian. English stays unprefixed at /; every other locale lives under /{locale}/... with identical slugs (/de/tools, /de/myfitnesspal-mcp — slugs are never localized, only content). src/routes.ts is the single source of truth for locale/route data (LOCALES, PAGE_ROUTES, ALT_PAGES, pathFor/urlFor/hashPath helpers) — it has no Supabase or other side-effecting imports, unlike src/index.ts, so it's safe to import directly from generators and tests instead of regex-scraping source text (src/alt-pages.test.ts used to have to do that; it doesn't anymore).

Content model: every page type is generated, in every locale including English, from typed TypeScript data — never hand-authored HTML sitting next to generated translations. src/copy/legal.ts (privacy/terms) is the pattern: a LegalDoc interface plus PRIVACY/TERMS objects typed Partial<Record<SiteLocale, LegalDoc>>. The Partial is deliberate and temporary — translation lands one locale at a time, so requiring every key up front would force placeholder content. Once every locale in LOCALES has a real (translated, not just present) entry, tighten both to Record<SiteLocale, LegalDoc> so bun run typecheck — which is src/-scoped and CI-gated, unlike scripts/ — refuses to compile a locale that forgot a document. That's the whole enforcement mechanism for translation completeness: the type system, not a hand-written test. src/copy/tools.ts (ToolsDoc) and src/copy/index.ts (IndexDoc) follow the identical shape for /tools and the landing page; all locales (de/es/fr/nl/pl/it/uk/ja) are populated for every content file, each locale's translated constant living in its own <name>.<locale>.ts file (e.g. src/copy/tools.de.ts) and merged into the shared Partial<Record<SiteLocale, …>> object in <name>.ts — one file per locale keeps a single translation pass a self-contained diff instead of one shared file seven agents would race on.

The header nav, mobile menu, and footer are shared by every generator (nav()/footer() in scripts/site-partials.ts) and were the one piece of chrome nobody translated: every HREF was already locale-aware (pathFor/hashPath), but every visible label was a hardcoded English string, so a fully-translated page still had an English menu bar and footer framing it on every locale. src/copy/chrome.ts (ChromeCopy) fixes this the same way as everything else — one file per locale, merged into CHROME_COPY, read via chromeFor(locale) inside nav()/footer(). A 7-locale native-level proofreading pass (one agent per locale, reviewing the actual rendered HTML, not the source data) is what caught this, along with several smaller gaps worth knowing about since they're easy to reintroduce: a translatable field added to an existing *Doc interface only helps once every generator call site that used to hardcode that string is updated to read from it (ToolsDoc.ui's parametersLabel/requiredLabel/optionalLabel/trySayingLabel fixed the same class of bug on /tools, where those 4 labels repeated ~20–40× per page); a raw-HTML field's aria-label needs translating too, not just its visible text (AltUiCopy.app.copyUrlAriaLabel); and a UI element that looks like a proper noun ("Claude"/"ChatGPT" tabs) can sit right next to one that isn't (IndexDoc.install.otherTabLabel, the "Other agents" tab) — both need the same review, not just the obvious one.

The /alternatives pages split translatable content into three layers, not one — a lesson learned from shipping the first two without the third and getting half-translated pages: src/copy/alternatives.ts's AppCopy (keyed by app slug) is the prose that genuinely differs per app — hub blurb, cons, the "moving from X" and "bring your history" sections, per-app FAQ extras; AltPageMeta in the same file is the <title>/description/og:description templates (an {app} placeholder standing in for the untranslated brand name); and src/copy/alt-ui.ts's AltUiCopy is everything else — the hero, the feature grid, install steps, the FAQ question/answer templates, section headings, and both closing CTAs — identical across all six comparison pages and the hub except for {app}. That third layer was the gap: AppCopy translated cleanly into all 7 locales while the surrounding template stayed English-only string literals in scripts/gen-alternatives.ts, so a "translated" /de/myfitnesspal-mcp page still greeted a German visitor in English everywhere except the per-app paragraphs. alt-ui.ts's doc comment marks which fields are raw HTML (contain <em>/<strong> tags or pre-escaped &amp;/&ldquo;/&rdquo; entities, inserted unescaped) versus plain text (escaped at render time) — a translation must preserve every tag, entity, and placeholder token ({app}, {link}, {copyUrl}, {apps}) verbatim. scripts/gen-alternatives.ts's featuresBlock()/installBlock()/faqsFor() read from altUiFor(locale) and substitute placeholders at render time; FEATURE_ICONS stays a fixed array in the generator (icons are structural, matched to AltUiCopy.app.features by index, never translated).

Troubleshooting lives at the bottom of /tools (/tools#troubleshooting, with a "Help" pill after the category pills, and a footer link from every page — chrome.ts's footer.troubleshooting, which must equal each locale's ToolsDoc.troubleshooting.title, pinned by src/site-copy.test.ts), not on its own route: ToolsDoc.troubleshooting (pillLabel/title/description plus items: Record<TroubleshootingId, TroubleshootingEntry>, so typecheck fails for a locale missing an entry), in the order of TROUBLESHOOTING_IDS in src/copy/tools.ts. Each id is the <details> DOM id, never translated, and deep-links (/tools#wrong-day opens that entry via the small script in gen-tools.ts). answerHtml is trusted, unescaped HTML that may link only to #anchors (a tool id or another troubleshooting id), https:// or mailto: — never a site-relative /… path, because plain data has no pathFor() and a translated page would link back to English. No FAQPage JSON-LD. The copy restates constants from the code — LIMIT_PER_WINDOW, AUTH_LIMIT_PER_WINDOW, BAN_STRIKE_THRESHOLD and BAN_DURATIONS_MS (src/rate-limit.ts), SESSION_TTL_MS and REFRESH_TOKEN_TTL_SECONDS (src/oauth.ts; the 24h access-token TTL is deliberately not stated, since refresh keeps a connection alive), EXPORT_TTL_SECONDS (src/export.ts) — so changing any of them means updating all 9 tools*.ts files and README's Troubleshooting section; src/site-copy.test.ts pins the numbers. Its prose mailto: and GitHub issues/security links are stripped by two tools.html rules in scripts/depersonalize.ts.

Generators: scripts/gen-legal.ts (privacy/terms), scripts/gen-tools.ts (/tools), scripts/gen-index.ts (the landing page), and scripts/gen-alternatives.ts (/alternatives + the 6 comparison pages) all follow the same shape — render English to public/<file> and every populated locale to public/{locale}/<file>. Re-run a generator after editing its data file; regenerate public/sitemap.xml via scripts/gen-sitemap.ts after that (it walks PAGE_ROUTES × SITE_LOCALES and only emits a <url> for a locale/page pair that actually exists on disk — an entry is a promise to crawlers, and a page that isn't built yet would 500). A fact repeated inside nav()/footer() is not owned by any single generator: editing chrome.ts means re-running all five generators, not just the one whose own data file changed, or every other page keeps the stale value while the one page you meant to fix is correct. src/site-copy.test.ts pins specific phrases (e.g. that caffeine is named everywhere the nutrient set is enumerated) directly against the source data files (src/copy/alt-ui.ts, not scripts/gen-alternatives.ts) plus the regenerated HTML — so both the data and the regeneration have to be right, and the test survives content moving between generator and data file as it did here.

In-prose cross-links are a trap: a LegalDoc paragraph that links to the other legal doc (e.g. privacy → terms) can't call pathFor(locale, ...) itself — it's plain data, not a template — so it's written as href="/terms" data-legal-link="terms" and scripts/gen-legal.ts's localizeCrossLinks() rewrites the href to the locale-correct path at render time. Forgetting this is exactly how a translated page ends up silently linking back to the English version (caught once already, live, before this existed).

hreflang/canonical: scripts/site-partials.ts's localeHead(locale, suffix) emits a self-referencing canonical (never canonical-to-English — that tells Google the translation is a duplicate) plus reciprocal hreflang links for every SITE_LOCALES entry, x-default → English, and og:locale/og:locale:alternate. nav() also renders a language switcher (a <details>/.lang-switch disclosure, light-dismissed via site.js) from the same reciprocal-URL data. src/alt-pages.test.ts asserts hreflang is fully reciprocal and every canonical is self-referencing, scoped to generator-produced pages (detected by generatedBanner()'s HTML comment) — which by now is every page, index.html and tools.html included, since both moved off hand-authored HTML onto gen-index.ts/gen-tools.ts.

Translation is fully AI-generated, no human review pass (a deliberate choice, most consequential on src/copy/legal.ts — treat that file as the one most worth a native-speaker legal review before relying on it). Every translated page carries TRANSLATION_NOTICE (src/routes.ts) linking to the same page in English; the privacy policy and terms carry the stronger LEGAL_TRANSLATION_NOTICE instead (translationNotice(locale, suffix, "legal") in gen-legal.ts), which says the translation may contain mistakes and the English version is the one that applies. Brand names are never inflected in any locale ("w serwisie GitHub", "za pośrednictwem serwisu Patreon", not "na GitHubie"/"na Patreonie"; same for Claude, ChatGPT and the app names): besides reading as product names, scripts/depersonalize.ts matches the base forms only, and a Polish pass that declined GitHub and Patreon left the maintainer's links on a self-hoster's pl/terms.html. public/llms.txt stays English-only (it's an AI-crawler ingestion doc, not a search-engine surface) but names the translated locales in prose. scripts/depersonalize.ts discovers public/{locale}/*.html at run time (mirroring how it already discovers public/alternatives/*.html) so a self-hoster's GA tag / GitHub links / contact email get stripped from every locale, not just English.

public/login.html is translated too, but it's a genuinely different case — it has zero SEO surface (reachable only via GET /authorize, not in the sitemap, <meta name="robots" content="noindex, nofollow">) and no fixed URL to hang a locale prefix off of: it's rendered per in-flight OAuth session by renderLoginPage() in src/oauth.ts, not routed by path. scripts/gen-login.ts + src/copy/login.ts follow the same typed-data-and-generator pattern as everywhere else, but the generated file is still a template — {{SESSION_ID}}/{{ERROR}} (unchanged) plus {{LANG_SWITCHER}} and {{LANG_SWITCHER_MENU}} tokens that nav()'s dynamicSwitcher option emits in place of the normal static header switcher and the sheet menu's language grid (the grid is the only switcher a phone gets, since .head-tools is hidden below 700px), because this page's switcher links have to carry the in-flight session's state/redirect_uri/client_id (reconstructed by authorizeUrl() in oauth.ts), not a fixed pathFor(). A {{CLIENT_NOTICE}} token under the page's subtitle is replaced per session by renderClientNotice() with the consent notice naming where the user will be sent back (see "OAuth" above); its three strings are LOGIN_CLIENT_NOTICE in src/copy/login.ts (one LOGIN_CLIENT_NOTICE_<LOCALE> per login.<locale>.ts), each keeping its {host} placeholder verbatim. OAuthSession carries a locale field, chosen once at GET /authorize (from an optional ?locale= query param the switcher sets — clicking a switcher link re-enters /authorize and mints a fresh session, which is fine since nothing's been submitted yet) and reused for every re-render of that same flow (a failed password or Google sign-in) so an error doesn't silently snap the page back to English. The email form has two submit buttons, action=signin (LoginDoc.signInButton) and action=signup (LoginDoc.createAccountButton); see "Sign-up is an explicit action" under OAuth. Locale availability is checked by file existence on disk at request time (availableLoginLocales()), not by importing src/copy/login.ts's LOGIN keys — deliberately mirroring how src/index.ts's static locale routes decide availability, so oauth.ts doesn't need to import the content module. Every error the page shows is translated (LOGIN_ERRORS in src/copy/login.ts): the two Google-flow strings plus invalidCredentials, signInFailed, weakPassword, passwordTooLong, emailInvalid and signUpFailed, chosen by the typed error code. Supabase Auth's own message text is never rendered — it is untranslated third-party text, and on the sign-in path it would reveal whether an address has an account.


Claude Code Operating Instructions

Core Philosophy

Default to parallel execution and web-verified information. Sequential execution and offline assumptions are fallback modes, not defaults. When in doubt: parallelize, then search.


1. Parallelization Protocol

Default Behavior: Parallel-First

Before starting any multi-step task:

  1. Decompose the full task into atomic subtasks
  2. Build a dependency graph — identify which subtasks have no prerequisite outputs
  3. Dispatch ALL dependency-free subtasks simultaneously using parallel tool calls
  4. Only after their completion, dispatch the next wave of now-unblocked subtasks
  5. Repeat until task is complete

Rule: If two tasks do not share an input/output dependency, they MUST run in parallel. Sequential execution of independent tasks is a performance violation.

Parallel Tool Call Patterns

Prefer batching tool calls in a single response turn rather than sequential turns:

# CORRECT — dispatch independent reads simultaneously
- Read file A
- Read file B
- Search web for library version
(all in one turn)

# WRONG — needless sequencing
- Read file A → wait → Read file B → wait → Search web

Sub-Agent Parallelization (Task Tool)

When using the Task tool to spawn sub-agents:

  • Spawn all independent sub-agents in a single dispatch batch
  • Maximum 5 concurrent sub-agents at any time to avoid context exhaustion
  • Each sub-agent must have a clearly scoped, non-overlapping responsibility
  • Define explicit output contracts for each agent before spawning
  • After all agents complete, explicitly synthesize their outputs — do not present raw agent outputs as the final answer

TodoWrite Protocol

When managing complex tasks with TodoWrite:

  • Mark tasks as in_progress before starting a parallel batch
  • Track each parallel thread separately
  • Never mark a parent task completed until all parallel children resolve
  • Flag dependency chains explicitly in todo descriptions

When Sequential Execution Is Permitted

Sequential execution is only justified when:

  • Task B requires Task A's output as direct input
  • Tasks write to the same file or resource (race condition risk)
  • A previous parallel batch returned an error that changes downstream logic
  • User explicitly requests step-by-step confirmation

In all other cases: parallelize.


2. Web Search Mandate

Search-First Triggers

Always perform a web search before proceeding when the task involves any of the following:

CategoryExamples
Library / framework versions"What's the latest stable version of X?"
API behavior and signaturesAny external SDK, REST API, or CLI tool
Security advisoriesCVEs, deprecated patterns, breaking changes
Best practicesArchitecture patterns, language idioms updated post-2024
Configuration optionsTool flags, environment variables, cloud service settings
Error messagesUnfamiliar stack traces, runtime errors
Compatibility questionsNode/Python/Rust version support, browser APIs
Pricing or limitsCloud service quotas, rate limits, SLA details

Search Behavior Rules

  1. Search before assuming. Do not rely on training knowledge for anything that changes over time. External information has a shelf life; always verify.
  2. Prefer official sources. When web results conflict, prioritize: official docs > GitHub releases > well-known technical blogs > forums.
  3. Deduplicate within session. If you have already searched for a query in this session and the result was unambiguous, do not re-search the same query. Cache the result mentally and reference it.
  4. Surface what you found. When you use web search to inform a decision, briefly state the source and key fact. Do not silently use search results without attribution.
  5. Parallelize searches. When multiple independent facts need to be looked up, dispatch all web searches simultaneously, not sequentially.
  6. Do not search for: Internal project details, proprietary architecture, code that exists in the repository (read the file instead), or subjective style decisions.

When Web Search Results Conflict with the Codebase

If web search returns guidance that contradicts patterns already established in the repo:

  1. Note the conflict explicitly
  2. Present both the current repo pattern and the web-sourced alternative
  3. Do not silently override existing code with web-sourced patterns without user confirmation

3. Session Start Checklist

At the beginning of every new task or session, run the following in parallel:

  • Read CLAUDE.md (this file) to confirm operating rules are loaded
  • Identify the task's scope and decompose into subtasks
  • Flag any subtasks that require web verification
  • Check for existing relevant files in the repo before searching externally
  • Dispatch first parallel batch

4. Quality and Safety Rules

  • No unverified version pinning. Never write a dependency version (package.json, pyproject.toml, Cargo.toml, etc.) without confirming via web search that it is current and non-deprecated.
  • No silent failures in parallel batches. If one parallel subtask fails, halt dependent tasks immediately and report the failure before proceeding.
  • Conflict resolution in parallel file edits. If two parallel sub-agents are asked to modify the same file, serialize those specific edits. All other work continues in parallel.
  • Do not hallucinate tool flags or API parameters. If unsure whether a CLI flag exists, search first.

5. Communication Standards

  • When executing a parallel batch, briefly state what is running in parallel and why
  • When web search informs a decision, cite source and date if available
  • When sequential execution is chosen over parallel, briefly state the dependency that forced it
  • Keep explanations concise — action over narration

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.