@cyanheads/faostat-mcp-server
Provides tools for querying FAOSTAT, the UN Food and Agriculture Organization's global agriculture statistics database, enabling access to crop production, trade, food balances, and more for 245+ countries from 1961 to present.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@@cyanheads/faostat-mcp-serverWhat is the rice production in Vietnam in 2020?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Public Hosted Server: https://faostat.caseyjhand.com/mcp
Overview
Global food and agriculture statistics from the UN's FAOSTAT: production, trade, food balances, food security, land use, fertilizer, and emissions for 245+ countries and territories since 1961. Resolve commodity and country codes, query the data, and run SQL over large results.
Tools
Tool | Description |
| Discover FAOSTAT statistical domains with codes, descriptions, last-update date, upstream row count, and local index status. The entry point — every query keys on a domain code. |
| Resolve human terms to the opaque integer codes a query needs (areas, items, elements), flagging each area as a country or an aggregate region. |
| Query a domain's cube by area(s), item(s), element(s), and year range. Inline preview for small results; large sets spill to a DataCanvas table. |
| Workflow: assemble top producers, the production trend, and trade flows for one commodity from the production and trade domains in a single call. |
| Run a read-only SQL |
| List the canvas tables staged this session, each with provenance, row count, and column schema. |
| Drop one staged canvas table before its 2-hour TTL. Opt-in — callable only with |
Related MCP server: Zaia
Capability reference
faostat_list_domains tool
Full FAOSTAT catalog (~69 domains) read live from the bulk manifest, annotated with local mirror status
codefor an exact domain lookup;topicsubstring filter over code/name/topic;indexed_onlyto list only domains queryable from the local mirroroffset+limit(max 200, default 20) page the catalog — response reportstotalMatches,truncated, andnextOffsetEach entry reports
indexed/index_readyflags, local row count, and last completed sync
faostat_resolve_codes tool
FTS5 full-text
query, substringname_contains, or exactcodelookup within adimension:area,item, orelementItem/element matches are scoped to codes present in the given
domain's cube; area codes are shared across domainsEvery area match is flagged
countryoraggregate(codes ≥ 5000, plus curated sub-threshold roll-ups such as China=351)limit(max 200, default 50) +offsetpage the match setTyped errors:
unknown_domain,index_not_ready,query_timeout
faostat_query_observations tool
Filters by
area_codes/item_codes/element_codesand an inclusiveyear_start/year_endrangeAggregate regions excluded by default (
include_aggregates: false); explicitarea_codesbypass the exclusionlimitcaps the inline page (default 200, max 1000); a match that exceeds it spills in full to a DataCanvas table (50,000-row staging cap) —faostat_dataframe_describefor its columns, then SQL viafaostat_dataframe_queryEvery row carries its data-quality
flag(A/E/I/B/M/T/X, others per domain) — never droppedTyped errors:
domain_not_indexed,index_not_ready,canvas_disabled,canvas_not_found,invalid_year_range,query_timeout
faostat_commodity_profile tool
Selects one QCL item with
item_codeoritem_query(code takes precedence), then ranks top producers/exporters/importers and returns an annual production trendQuery selection prefers a unique exact label after trimming, collapsing whitespace, and case folding; otherwise requires a unique relevance match. For ambiguous terms such as
maizeormilk, callfaostat_resolve_codeswithdomain: "QCL",dimension: "item", and the query, then pass the selecteditem_code(e.g.56for maize grain)Rankings are per-country sums grouped by unit, each country at its own latest reporting year; countries only (aggregates excluded)
Returns a partial, production-only profile with a notice — rather than failing — when the trade domain (TCL) isn't indexed or still syncing
top_ncaps each ranked list (max 50); when the merged observation set is too large to inline it spills to a DataCanvas table —faostat_dataframe_describefor its columns, thenfaostat_dataframe_queryfor further SQLEvery staging outcome is stated in the notice: the staged table, a set that fit inline, a staging failure, or a disabled canvas
Typed errors:
missing_item,ambiguous_item,no_match,domain_not_indexed,index_not_ready,invalid_year_range,canvas_not_found,query_timeout
faostat_dataframe_query tool
Single-statement read-only
SELECTover stagedfaostat_xxxxxxxxtables — joins, aggregates, window functions, and CTEs all workWrites, DDL,
DROP,COPY,PRAGMA,ATTACH, external-file functions, and system catalogs (information_schema,sqlite_master,duckdb_*) are rejectedEngine-setting introspection,
query_table, dynamicquery()SQL, and file table references are rejected;query()with a single literal read-onlySELECTremains supportedrow_limitcaps the response (default 1000, max 10000);truncatedmeans more rows exist, with no exact total computed on this pathTyped errors:
canvas_disabled,canvas_not_found,missing_table,system_catalog_access,invalid_sql
faostat_dataframe_describe tool
Lists staged tables with source tool, query params, row count, column schema, and recorded creation/expiry timestamps
namedescribes one table outright; otherwiseoffset+limit(max 100, default 20) page the listing newest-firstTyped errors:
canvas_disabled,canvas_not_found,missing_table
faostat_dataframe_drop tool
Opt-in: registered disabled — listed on the landing page with its enable hint, absent from
tools/list— unlessFAOSTAT_DATAFRAME_DROP_ENABLED=trueDrops one staged
faostat_xxxxxxxxtable and its provenance from the session canvas, or from the canvas acanvas_idnamesIdempotent: a name not staged on that canvas returns
dropped: falsewith a notice and changes nothingTyped errors:
canvas_disabled,canvas_not_found
Features
The faostat-guide covers comparable reporting years, country versus regional totals, units, coverage, and complete SQL analysis across staged results. It ships with plugin, npm, Docker, and MCPB installs and is served through the MCP Skills extension as a skill resource.
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.
FAOSTAT-specific:
Persistent local SQLite mirror of the FAOSTAT bulk corpus via the framework
MirrorService, with FTS5 over the dimension labels driving code resolutionStreaming bulk-ZIP ingester — skips domains whose upstream update date hasn't advanced, and stream-parses the normalized CSV into SQLite without materializing the full file in memory
Config-driven domain selection (
FAOSTAT_DOMAINS) — the indexed set can grow without code changes, and the full catalog stays browsable regardlessDataCanvas SQL surface (DuckDB) for
GROUP BY, ranking, and time-series analysis over spilled result sets
Agent-friendly output:
Country-vs-aggregate classification on every area, with aggregates excluded from sums by default — guards against double-counting World/continent rows with their member countries
Data-quality provenance — every observation carries its FAOSTAT flag (
A/E/I/B/M/T/X, others per domain), never dropped from outputGraceful partial results —
faostat_commodity_profilereturns a production-only profile with a notice, rather than failing, when the trade domain isn't indexedTyped error contracts —
index_not_ready,domain_not_indexed,canvas_disabled, and others each carry a concrete recovery hint
Getting started
Connect to the hosted instance, no install:
claude mcp add --transport http faostat-mcp-server https://faostat.caseyjhand.com/mcpOr run it locally after building the mirror:
claude mcp add faostat-mcp-server -- npx -y @cyanheads/faostat-mcp-serverFor other clients, add this to the MCP config file:
{
"mcpServers": {
"faostat-mcp-server": {
"command": "npx",
"args": ["-y", "@cyanheads/faostat-mcp-server"]
}
}
}The bulk-download service is public and keyless. For Docker or a source build, see Running the server.
Configuration
Variable | Description | Default |
| Comma-separated FAOSTAT domain codes to index into the local mirror. Domains outside this set appear in |
|
| Directory holding the per-domain SQLite stores and the shared dimension database. Created if absent. |
|
| FAOSTAT bulk-download service base URL (manifest + per-domain ZIPs). |
|
| Cron for the in-process incremental refresh (HTTP transport only). Omit to disable and run | — |
| DataCanvas engine. |
|
| Set |
|
| Transport: |
|
| HTTP session mode: |
|
| Port for the HTTP server. |
|
| Auth mode: |
|
| Log level (RFC 5424). |
|
| Directory for log files (Node.js only). |
|
See .env.example for the full list of optional overrides.
Running the server
Local development
Requires Bun v1.4.0 or higher (or Node.js v24+), plus disk for the mirror. The default domain set (QCL,TCL,FBS,FS,RL,GLE,RFN,QV, ∼37M rows) needs a few GB; drop TCL (∼17M rows) from FAOSTAT_DOMAINS on a constrained host.
git clone https://github.com/cyanheads/faostat-mcp-server.git
cd faostat-mcp-server && bun install
cp .env.example .env
# Override the default domain set, mirror path, or refresh cron in .env.Build and run:
# One-time build bun run rebuild # Run the built server bun run start:stdio # or bun run start:httpRun checks and tests:
bun run devcheck # Lint, format, typecheck, security bun run test # Vitest suite under Bun, then under Node bun run lint:mcp # Validate MCP definitions against spec
Building the mirror
The corpus is not bundled. Before the data tools can answer queries, sync the selected domains into the local mirror:
bun run mirror:init # one-time bootstrap — downloads and indexes the FAOSTAT_DOMAINS set
bun run mirror:refresh # re-sync domains whose upstream update date has advanced; build missing planner statistics
bun run mirror:verify # report sync status, local row counts, and sample readsmirror:init is idempotent and resumable per domain — re-running after an interrupt re-streams only the unfinished domain ZIP. FAOSTAT_DOMAINS selects which domains are indexed; everything else in the catalog shows in faostat_list_domains with indexed: false until added and re-synced. On HTTP transport, set FAOSTAT_REFRESH_CRON to refresh in-process on a schedule; on stdio, run mirror:refresh out-of-band. The read tools return index_not_ready until the first sync completes.
mirror:refresh also builds query-planner statistics (ANALYZE) for any selected domain that has none, even when its data is unchanged upstream — a mirror synced by an older release, or one whose last build failed. Otherwise the server builds them itself, in the background on a worker thread, the first time a data read touches that domain, and keeps answering meanwhile.
Docker
docker run --rm -p 3010:3010 -v faostat-mirror:/usr/src/app/.faostat-mirror ghcr.io/cyanheads/faostat-mcp-server:latestBuild locally with docker build -t faostat-mcp-server .. For stdio from an MCP client, use "command": "docker" with "args": ["run", "-i", "--rm", "-e", "MCP_TRANSPORT_TYPE=stdio", "-v", "faostat-mirror:/usr/src/app/.faostat-mirror", "ghcr.io/cyanheads/faostat-mcp-server:latest"]. The image defaults to HTTP transport, stateless session mode, and logs to /var/log/faostat-mcp-server. A dedicated dependency stage installs the production tree for the target platform (DuckDB's prebuilt native binding included), so the slim runtime image carries no build toolchain and a multi-arch build never runs Bun under emulation. OpenTelemetry peer dependencies are installed by default — build with --build-arg OTEL_ENABLED=false to omit them. Mount a volume at the mirror path to persist the corpus across container recreations, and bootstrap it inside the container:
docker exec <container> bun run mirror:init # one-time bootstrap
docker exec <container> bun run mirror:verify # sync status + sample reads
docker exec <container> bun run mirror:refresh # re-sync updated domains; build missing planner statisticsProject structure
Directory | Purpose |
|
|
| Server-specific environment variable parsing and validation with Zod. |
| Published agent guide, also served as an MCP skill resource. |
| Tool definitions ( |
| The bulk-download mirror service — manifest discovery, streaming ZIP ingester, CSV parsing, dimension store, SQLite-backed |
| DataCanvas accessor and the spill/query/describe/drop staging layer. |
|
|
| Unit and integration tests mirroring |
Development guide
See CLAUDE.md/AGENTS.md for development guidelines and architectural rules. The short version:
Handlers throw, framework catches — no
try/catchin tool logicUse
ctx.logfor request-scoped logging,ctx.statefor tenant-scoped storageRegister new tools in the
createApp()array insrc/index.tsWrap external data: validate raw → normalize to domain type → return output schema; never fabricate missing fields, and carry the data-quality flag through
Data attribution
Data is sourced from FAOSTAT, the statistics division of the Food and Agriculture Organization of the United Nations (FAO). FAOSTAT data is published under CC BY-4.0; cite FAO as the source in downstream use. This project is not affiliated with or endorsed by the FAO.
Contributing
Issues are welcome. Run checks and tests before submitting:
bun run devcheck
bun run testLicense
Apache-2.0 — see LICENSE for details.
This server cannot be deployed
Maintenance
Related MCP Connectors
FAOSTAT MCP — the UN Food and Agriculture Organization's statistics service.
Data Commons MCP — harmonised public statistics for places, from Google Data Commons (REST v2).
UN Comtrade international trade statistics via MCP. Country/HS lookups, flows, balances, rankings.
Query, join, profile, clean and convert CSV/JSON/Parquet with server-side DuckDB over MCP.
Related MCP Servers
- AlicenseBqualityAmaintenanceEnables AI assistants to query the full FAOSTAT API for global food and agriculture statistics, allowing natural-language questions about crop production, trade, food security, emissions, and more.2389 PyPI18MIT
- AlicenseNot gradedqualityDmaintenanceMCP server that exposes SQLite datasets as queryable tools and resources via Streamable HTTP, enabling read-only exploration and SQL queries.Apache 2.0

mcp-fasofficial
AlicenseNot gradedqualityBmaintenanceEnables access to USDA Foreign Agricultural Service trade and global production data through MCP, supporting natural language queries and tool-based data retrieval.456 npmMIT- AlicenseNot gradedqualityBmaintenanceMCP server for accessing USDA National Agricultural Statistics Service (Quick Stats) data, enabling natural language queries about agricultural statistics.5 npmMIT