
usda-mcp-server
io.github.cyanheads/usda-mcp-server
Search foods, compare nutrients, and look up the full USDA FoodData Central database.
Documentation
@cyanheads/usda-mcp-server
Search foods, compare nutrients, and look up the full USDA FoodData Central database via MCP. STDIO or Streamable HTTP.
Public Hosted Server: https://usda.caseyjhand.com/mcp
Overview
Nutrition data for roughly 400,000 foods from USDA FoodData Central, the US government's authoritative food composition database. Search by keyword or UPC, pull full nutrient profiles scaled to any portion, and compare foods side by side.
Tools
| Tool | Description |
|---|---|
usda_search_foods | Search foods by keyword, ingredient, or UPC/GTIN across SR Legacy, Foundation, Survey (FNDDS), and Branded data sources |
usda_get_food | Full nutrient profile for one food by FDC ID, with optional per-portion scaling |
usda_get_foods | Batch nutrient fetch for 2–500 FDC IDs, 20 distinct IDs per call |
usda_compare_foods | Side-by-side nutrient comparison for 2–5 foods, formatted as a markdown table |
usda_list_nutrients | Static FDC nutrient reference table (~150 nutrients) with IDs, names, units, and categories |
Resources
| Resource | Description |
|---|---|
usda://food/{fdcId} | Full nutrient profile for a specific food by FDC ID |
usda://nutrients | Complete FDC nutrient reference list |
skill://usda-guide/SKILL.md | Food selection, serving-weight, and missing-nutrient guidance for agents |
Food profiles and the nutrient reference are also reachable via tools. Use usda_search_foods to discover FDC IDs before reading food resources.
Capability reference
usda_search_foods tool
- Query by keyword, ingredient name, or UPC/GTIN code; optional
dataType[]filter across SR Legacy, Foundation, Survey (FNDDS), and Branded. WithoutdataTypethe search covers["SR Legacy"],["Branded"]oncebrandOwneris set, or["Branded", "Survey (FNDDS)"]when the query is 8–14 digits alone (a UPC/GTIN barcode or an FNDDS food code); a barcode matches the BrandedgtinUpc. A 12-, 13-, or 14-digit code with a valid GTIN check digit also matches the other forms FDC stores that GTIN in (leading zeros added or dropped down to 12 digits, and the 12-digit form without its check digit) in the same call, and each row keeps its storedgtinUpc; any other code matches only as FDC stores it. A barcode query that finds nothing hints at a product-name search withdataType: ["Branded"] - A food matching any one query word counts;
requireAllWords: truerequires every word."quoted phrases",OR, and the other Lucene operators keep their meaning brandOwnerandfoodCategoryfilters match as one phrase, ignoring case and punctuation; a value containing*or?is sent as wildcard terms, each word matched on its own (Poult*); a whole word followed by*can match nothing (Poultry*does), so shorten it.pageSize(max 50, default 10) andpageNumberpaginate- Returns FDC IDs plus available preview nutrients: protein (1003), fat (1004), carbohydrate (1005), fiber (1079), and energy (1008, 1062, 2047, 2048). Original values, units, order, and distinct energy estimates are preserved; missing entries are omitted. Use
usda_get_foodfor other nutrients or the full profile - Each food carries
basisUnit— what the nutrient amounts are per 100 of:g,mlfor a Branded label in ml or MLT, or absent when the label unit (IU, MG, or none) fixes neither, in which case the amounts are per 100 label units and the basis is unverified. Branded foods also returngtinUpc - FDC serves only the first 100,000 results of a search. A page past that window fails with
result_window_exceeded(naming the last reachable page); a page past the last page returns emptyfoods[], the requested page, totals, and a notice with a validpageNumberwhen the query has matches - Typed errors:
query_empty(blank query),query_syntax(FDC rejected the query syntax),no_results(nothing matched in the requested data sources),result_window_exceeded(pageSize×pageNumberbeyond the first 100,000 results),retry_deadline_exceeded(FDC did not answer within the call's 45 s budget; retry once)
usda_get_food tool
- Full nutrient profile for one
fdcId; optionalnutrients[]filter to specific IDs, with requested IDs the food does not report listed inmissingNutrients - Values are per 100 of
basisUnit:gfor every non-Branded food and for Branded labels ing/GRM/GM,mlfor Branded labels in ml or MLT, absent when the label unit fixes neither (basis unverified, per 100 label units). Branded foods also returngtinUpc,servingSize,servingSizeUnit, andhouseholdServingFullText - Optional
unit(g/oz/lb/kg/serving) with an optionalquantityscales every value from that per-100 basis;quantitydefaults to 100 for mass units and 1 forserving. Serving uses the valid portion FDC displays first (lowestsequenceNumber), or a positive finite Branded label size ing/GRM/GM(case-insensitive) when no portion exists, multiplied byquantity. On anmlor label-unit basis a mass unit is applied to that basis unconverted, and a notice says so servingInfoidentifies the resolved portion or label serving and its gram weight;allPortions[]contains actual portion definitions only, in FDC's display order (ascendingsequenceNumber, ties as FDC lists them, unnumbered portions last), soservingInfois the first entry whenever a food has portions. Each portion carriesamount(how many of the described unit the gram weight covers) when FDC sends one- Typed errors:
not_found(bad FDC ID),quantity_without_unit,no_portion_data(no valid portion or supported Branded gram label),retry_deadline_exceeded(FDC did not answer within the call's 45 s budget; retry once). Volume, IU, milligram labels, missing units, and invalid sizes require an explicit mass-unit request; no density is inferred
usda_get_foods tool
- Batch fetch in one call; accepts 2–500
fdcIdsentries, drops repeats, fetches the first 20 distinct IDs, and returns the rest indeferredIdswith a notice naming the follow-up call (a single deferred ID goes tousda_get_food).foods[]andfailed[]cover only the fetched IDs.USDA_CLAMP_LIMITS=falserejects more than 20 entries instead - The batch is one
/foodsrequest. If its 15 s attempt times out (slow Foundation records, most often), each ID is refetched on its own inside the call's 45 s budget, at most 10 in flight across the server. IDs FDC does not return in time, or keeps failing on, joindeferredIdsahead of those past the first 20, and the notice names them;usda_get_foodcan fetch one at a time - Values are per 100 of each food's
basisUnit(no portion scaling); each entry also carriesservingSizeUnitfor Branded foods nutrients[]filter strongly recommended — full profiles for 20 foods are large. Requested IDs a food does not report are listed in itsmissingNutrients- Per-ID partial failure — IDs that return no data land in
failed[]instead of aborting the batch; when every ID is unknown,foods[]is empty andfailed[]holds them all - Typed error:
retry_deadline_exceededwhen FDC answered none of the fetched IDs within the call's 45 s budget (retry once, or request fewer foods)
usda_compare_foods tool
- Side-by-side comparison for 2–5 FDC IDs, pivoted one row per nutrient and one column per food
- Defaults to 12 commonly compared nutrients (energy, protein, fat, saturated fat, carbs, fiber, total sugars, sodium, potassium, calcium, iron, vitamin C) unless
nutrients[]is given. Under the defaults, a food missing energy (1008) is filled from 2048, then 2047, and one missing total sugars (2000) from 1063; each fill is listed insubstitutions[](fdcId,requested,used) rather thanmissingData[]. An explicitnutrients[]is compared as given, without fills - All values scaled to a common
quantity+unitbasis (default 100 g;quantityis an amount inunit, sounit: "oz"alone compares per 100 oz). A food whosebasisUnitisml, or absent, is compared on that basis without conversion and a notice names it - Proceeds with the valid foods when some IDs return no data; only throws
too_few_foodswhen fewer than 2 resolve - IDs FDC does not return before the call's 45 s deadline, or keeps failing on, are left out and listed in
deferredIdswith a notice; when that leaves fewer than 2 foods, the call fails withretry_deadline_exceeded(retry once, or fetch the IDs withusda_get_food), or withtoo_few_foodswhen even answers for the deferred IDs could not make 2 foods - Rows where every food is null for that nutrient are filtered out
usda_list_nutrients tool
- Static reference table of ~150 tracked FDC nutrients — no API call
- Optional
categoryfilter:macronutrients,vitamins,minerals,lipids,amino_acids,other - Returns each nutrient's ID, name, SR reference number, unit, and category — resolve a name to the ID used by
nutrients[]elsewhere
usda://food/{fdcId} resource
- Same data as
usda_get_foodwithout portion scaling, withportionsin the same display order — full nutrient profile per 100 ofbasisUnit(per 100 g, or per 100 ml for a Branded food labeled in ml; absentbasisUnitmeans a label unit that fixes neither) asapplication/json fdcIdmust be a bare positive integer (no sign, leading zero, decimal, or exponent); anything else throwsinvalid_idnot_foundwhen the ID doesn't exist in FDC;retry_deadline_exceededwhen FDC does not answer within the call's 45 s budget
usda://nutrients resource
- Complete FDC nutrient reference — same content as
usda_list_nutrientswith no category filter - Served as
application/jsonwith a 1-hour public cache hint, since the table is bundled at build time and identical for every caller
skill://usda-guide/SKILL.md resource
Guidance for matching food records, choosing a serving weight, and reporting incomplete nutrient coverage. The same usda-guide ships with plugin installs, npm, Docker, and the desktop bundle.
Features
Built on @cyanheads/mcp-ts-core: stdio and Streamable HTTP transports, pluggable auth (none / jwt / oauth), swappable storage (in-memory, filesystem, Supabase, Cloudflare KV/R2/D1), structured logging with optional OpenTelemetry tracing.
FoodData Central-specific:
- Type-safe client for the USDA FoodData Central REST API (
api.nal.usda.gov/fdc/v1) - Normalization layer that handles inconsistent API response shapes across search, single-food, and batch endpoints
- Batch API endpoint (
/foods) with per-food partial failure reporting; a batch that times out is refetched one ID per request, and IDs FDC does not return in time are deferred rather than failing the call - HTML response detection (rate-limit proxy returns 200 HTML) with service-unavailable error surfacing
- Static nutrient reference dictionary — ~150 nutrients with FDC IDs, SR numbers, units, and categories; no API call required
Agent-friendly output:
- Provenance preserved — FDC data source (
dataType) on every food result so callers know whether they're reading curated research data or label-derived branded values - Partial failure reporting — batch tools (
usda_get_foods,usda_compare_foods) return successes alongside structuredfailed[]/missingData[]/deferredIds[]entries rather than failing the whole request - Cross-reference hints — FDC IDs and tool names in descriptions so agents know exactly which call to make next (search → get → compare workflow)
Getting started
Connect to the hosted instance, no install:
claude mcp add --transport http usda-mcp-server https://usda.caseyjhand.com/mcp
Or run it locally:
claude mcp add usda-mcp-server -e USDA_FDC_API_KEY=your-key -- npx -y @cyanheads/usda-mcp-server
For other clients, add this to the MCP config file:
{
"mcpServers": {
"usda-mcp-server": {
"command": "npx",
"args": ["-y", "@cyanheads/usda-mcp-server"],
"env": { "USDA_FDC_API_KEY": "your-api-key" }
}
}
}
Get a free key at api.data.gov/signup. Food search, lookup, and comparison require it; the static nutrient reference works without it. For Docker or a source build, see Running the server.
Configuration
| Variable | Description | Default |
|---|---|---|
USDA_FDC_API_KEY | Required for FoodData Central-backed tools (search, get, batch, compare) — not for startup or usda_list_nutrients. Get a free key at api.data.gov. | — |
USDA_CLAMP_LIMITS | true: usda_get_foods fetches the first 20 distinct IDs of a larger request and returns the rest as deferredIds. false: it rejects more than 20 IDs. An empty value reads as unset (true); a value that is not a boolean string fails startup. | true |
MCP_TRANSPORT_TYPE | Transport: stdio or http. | stdio |
MCP_HTTP_PORT | Port for HTTP server. | 3010 |
MCP_AUTH_MODE | Auth mode: none, jwt, or oauth. | none |
MCP_LOG_LEVEL | Log level (RFC 5424). | info |
LOGS_DIR | Directory for log files (Node.js only). | <project-root>/logs |
STORAGE_PROVIDER_TYPE | Storage backend. | in-memory |
OTEL_ENABLED | Enable OpenTelemetry instrumentation (spans, metrics, completion logs). | false |
See .env.example for the full list of optional overrides.
Running the server
Requires Bun v1.4.4 or higher (or Node.js v24+).
Local development
git clone https://github.com/cyanheads/usda-mcp-server.git
cd usda-mcp-server && bun install
cp .env.example .env # set USDA_FDC_API_KEY
-
Build and run:
# One-time build bun run rebuild # Run the built server bun run start:stdio # or bun run start:http -
Run checks and tests:
bun run devcheck # Lint, format, typecheck, security bun run test # Vitest test suite bun run lint:mcp # Validate MCP definitions against spec
Docker
docker run --rm -e USDA_FDC_API_KEY=your-key -p 3010:3010 ghcr.io/cyanheads/usda-mcp-server:latest
The image defaults to HTTP transport, stateless session mode, and logs to /var/log/usda-mcp-server. For stdio, use docker run -i --rm -e MCP_TRANSPORT_TYPE=stdio -e USDA_FDC_API_KEY=your-key ghcr.io/cyanheads/usda-mcp-server:latest. To build locally, run docker build -t usda-mcp-server .; OpenTelemetry peer dependencies are installed by default — build with --build-arg OTEL_ENABLED=false to omit them.
Project structure
| Directory | Purpose |
|---|---|
src/index.ts | createApp() entry point — registers tools, resources, and inits FdcService. |
src/config | Server-specific environment variable parsing and validation with Zod (USDA_FDC_API_KEY, USDA_CLAMP_LIMITS). |
src/mcp-server/tools | Tool definitions (*.tool.ts) — search, get, batch, compare, list-nutrients. |
src/mcp-server/resources | Resource definitions (*.resource.ts) — food profile and nutrient reference. |
src/services/fdc | FdcService — USDA FDC API client, normalization, and static nutrient reference data. |
skills/ | Published guidance for agents calling the server. |
tests/ | Unit tests mirroring src/ — every tool, resource, and the FDC service. |
Development guide
See CLAUDE.md for development guidelines and architectural rules. The short version:
- Handlers throw, framework catches — no
try/catchin tool logic - Use
ctx.logfor request-scoped logging,ctx.statefor tenant-scoped storage - Register new tools and resources via the barrels in
src/mcp-server/*/definitions/index.ts - Wrap external API calls: validate raw → normalize to domain type → return output schema; never fabricate missing fields
Contributing
Issues are welcome. Run checks and tests before submitting:
bun run devcheck
bun run test
License
Apache-2.0 — see LICENSE for details.
@cyanheads/usda-mcp-servernpm install @cyanheads/usda-mcp-server@cyanheads/usda-mcp-servernpm install @cyanheads/usda-mcp-serverRemote
Related Servers
io.github.cyanheads/anime-mcp-server
Search anime/manga, franchise relations, schedule, characters, rankings, studio filmography.
io.github.cyanheads/art-institute-chicago-mcp-server
Search the Art Institute of Chicago collection: artworks, artists, exhibitions, and audio guides.
io.github.cyanheads/arxiv-mcp-server
Search arXiv, fetch paper metadata, and read full-text content.