@Cyanheads/Faostat Server
БесплатноНе проверенGlobal food & agriculture statistics from the UN FAOSTAT bulk-download corpus, served from a local SQLite mirror with a DataCanvas SQL surface, over MCP.
Описание
Global food & agriculture statistics from the UN FAOSTAT bulk-download corpus, served from a local SQLite mirror with a DataCanvas SQL surface, over MCP.
README
@cyanheads/faostat-mcp-server
Global food & agriculture statistics from the UN FAOSTAT bulk-download corpus, served from a local SQLite mirror with a DataCanvas SQL surface, via MCP. STDIO or Streamable HTTP.
Version License MCP SDK npm TypeScript Bun
Install in Claude Desktop Install in Cursor Install in VS Code
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 |
|---|---|
faostat_list_domains |
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. |
faostat_resolve_codes |
Resolve human terms to the codes a query needs (areas, items, elements), flagging each area as a country or an aggregate region and carrying its M49 code. |
faostat_query_observations |
Query a domain's cube by area(s), item(s), element(s), and year range. Returns pages of up to limit rows by an offset of at most 100,000; with DataCanvas on, a first page whose match exceeds limit also stages the whole match to a canvas table. |
faostat_commodity_profile |
Workflow: assemble top producers, the production trend, and trade flows for one commodity from the production and trade domains in a single call. The elements follow what the item carries: Production, or Stocks for live-animal items. trade_item_code ranks trade on another TCL item for crops traded mostly in processed form. |
faostat_dataframe_query |
Run a read-only SQL SELECT against the canvas tables staged by the analytical tools. |
faostat_dataframe_describe |
List the canvas tables staged this session, each with provenance, row count, and column schema. |
faostat_dataframe_drop |
Drop one staged canvas table before its 2-hour TTL. Opt-in — callable only with FAOSTAT_DATAFRAME_DROP_ENABLED=true. |
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(at most 200 per call, default 20; a larger value is served at 200 with a notice) page the catalog — response reportstotalMatches,truncated, andnextOffset- Each 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, orelement;code_textlooks up alphanumeric items, andm49_code(area only) looks up every area carrying an M49 code querywords are matched as prefixes, each distinct word searched once, and search time is linear in the query's length; quotes, parentheses, asterisks, and control characters separate words. A blank or*query lists the dimension; any other query made only of quotes, parentheses, asterisks, and whitespace is rejected asinvalid_querycode_textanditem_codes_textare case-insensitive: letters are uppercased before lookup- Item/element matches are scoped to codes present in the given
domain's cube; area codes are shared across domains - Element matches include observed
units;item_codesoritem_codes_textrestrict element discovery and units to selected items. Item/element lookups require that domain to be ready - Every area match is flagged
countryoraggregate(codes ≥ 5000, plus curated sub-threshold roll-ups such as China=351) and carriesm49_code, a string with its leading zeros (840,001); the excluding-intra-trade aggregates carry dotted FAO extensions such as002.03, so the codes are FAO's, not ISO numeric codes - Verified item groups are marked
aggregateby domain, including 24 Food Balances (FBS) groups and totals.kind: nullleaves group membership unknown limit(at most 200 per call, default 50; a larger value is served at 200 with a notice) +offsetpage the match set- Typed errors:
unknown_domain,index_not_ready,invalid_text_selector,invalid_m49_selector,invalid_item_scope,invalid_query,query_timeout,pool_closed
faostat_query_observations tool
- Filters by
area_codes/item_codes/item_codes_text/element_codes/source_codesand an inclusiveyear_start/year_endrange - Alphanumeric items retain their exact
item_code_textwithitem_code: null(item_codes_textletters are uppercased before the query); numeric items retain their integer code - Period observations retain
period(e.g.2000-2002) and use its midpoint asyearfor filtering. Censored values retain the numeric bound plusvalue_qualifier(e.g.<with2.5) - Every row carries
area_m49, the area's M49 code asfaostat_resolve_codesreports it, shown in anM49column - Source-specific rows carry
source_codeandsource; omittingsource_codesreturns all sources, which must be compared separately rather than summed - An empty query with explicit item and element selections returns
available_elementswith labels and units for those items; this does not establish coverage for the requested areas, years, or sources - Aggregate regions excluded by default (
include_aggregates: false); explicitarea_codesbypass the exclusion limit(default 200, at most 1000 per call; a larger value is served at 1000 withrequestedLimit/effectiveLimitand a notice) is the page size andoffsetits start;nextOffsetcontinues while rows remain, with or without DataCanvas, andtotalCountis exact up to 50,000 and on the last page, and on any other page a floor past 50,000, whichtotalCountIsFloor: truedisclosesoffsetreaches at most 100,000 rows into a match (a larger value is rejected); a page whose next page would start past that carries nonextOffset, and its notice says to partition the query byyear_start/year_endor narrower codes and page each part fromoffset0- With DataCanvas on, a first page (
offset0) whose match exceedslimitalso stages the whole match to a canvas table (50,000-row staging cap) —faostat_dataframe_describefor its columns, then SQL viafaostat_dataframe_query - Every row carries its data-quality
flag(A/E/I/B/M/T/X, others per domain) — never dropped - Typed errors:
domain_not_indexed,index_not_ready,canvas_not_found,invalid_year_range,conflicting_item_selectors,query_timeout,pool_closed
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 trend trade_item_code(a TCL item code) rankstop_exportersandtop_importers, their units, and the staged TCL rows on that item instead, for crops traded mostly in processed form (paddy rice 27 trades as rice milled equivalent 30); producers, the trend, and the element choice stay on the selected item.trade_itemechoes{ code, name }when the input was supplied and TCL is indexed and has finished its initial sync. Find the code withfaostat_resolve_codesondomain: "TCL"- The elements follow what the item carries: Production (5510) and tonne trade quantities (5610/5910) for an item with Production; for live-animal items, which have none, their Stocks elements (5111, 5112, 5114) and every import/export quantity element they carry, grouped by unit.
ranking_elementsnames each ranking's elements and units, and the section headings repeat them - Query selection prefers a unique exact label after trimming, collapsing whitespace, case folding, and comparing
;and,alike (Peas, dryselectsPeas; dry); otherwise requires a unique relevance match. For ambiguous terms such asmaizeormilk, 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;
years_behindmarks how far a row trails its ranking's latest year, and the notice names lagging rows with ayear_startthat drops them; countries only (aggregates excluded) - Returns a partial profile without trade, with a notice — rather than failing — when the trade domain (TCL) isn't indexed or has no completed sync
top_ncaps each ranked list (at most 50 per call; a larger value is served at 50 with a notice); 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 SQL- Every 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,invalid_query,ambiguous_item,no_match,trade_item_not_found,domain_not_indexed,index_not_ready,invalid_year_range,canvas_not_found,query_timeout,pool_closed
faostat_dataframe_query tool
- Single-statement read-only
SELECTover stagedfaostat_xxxxxxxxtables — joins, aggregates, window functions, and CTEs all work - Writes, DDL,
DROP,COPY,PRAGMA,ATTACH, external-file functions, and system catalogs are rejected — including a column alias, CTE name, or table alias spelled like a DuckDB internal metadata view (such asduckdb_tablesorpg_tables); rename it. The same spelling inside a string literal is fine. - Engine-setting introspection,
query_table, dynamicquery()SQL, and file table references are rejected;query()with a single literal read-onlySELECTremains supported row_limitcaps the response (at most the canvas row limit per call —CANVAS_DEFAULT_ROW_LIMIT, 10000 unless configured — and default 1000, or that limit when it is lower); a larger value is served at that cap withrequestedRowLimit/effectiveRowLimitand a notice;truncatedmeans more rows exist, with no exact total computed on this path- Typed 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(at most 100 per call, default 20; a larger value is served at 100 with a notice) page the listing newest-first- Typed 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=true - Drops one staged
faostat_xxxxxxxxtable and its provenance from the session canvas, or from the canvas acanvas_idnames - Idempotent: a name not staged on that canvas returns
dropped: falsewith a notice and changes nothing - Typed errors:
canvas_disabled,canvas_not_found
Features
The faostat-guide covers reporting periods, censored values, source estimates, 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 resolution - Streaming 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 regardless - DataCanvas SQL surface (DuckDB) for
GROUP BY, ranking, and time-series analysis over staged 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 output - Graceful partial results —
faostat_commodity_profilereturns a profile without trade, with a notice, rather than failing, when the trade domain isn't indexed - Typed 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/mcp
Or run it locally after building the mirror:
claude mcp add faostat-mcp-server -- npx -y @cyanheads/faostat-mcp-server
For 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.
The Claude Desktop extension bundle runs over stdio with DataCanvas disabled. Use the npm package or container for DataCanvas SQL or Streamable HTTP.
Configuration
| Variable | Description | Default |
|---|---|---|
FAOSTAT_DOMAINS |
Comma-separated FAOSTAT domain codes to index into the local mirror. Domains outside this set appear in faostat_list_domains but are not queryable until added and re-synced. |
QCL,TCL,FBS,FS,RL,GLE,RFN,QV |
FAOSTAT_MIRROR_PATH |
Directory holding the per-domain SQLite stores and the shared dimension database. Created if absent. | ./.faostat-mirror |
FAOSTAT_BULK_BASE_URL |
FAOSTAT bulk-download service base URL (manifest + per-domain ZIPs). | https://bulks-faostat.fao.org/production |
FAOSTAT_REFRESH_CRON |
Cron for the in-process incremental refresh (HTTP transport only). Omit to disable and run mirror:refresh out-of-band. |
— |
CANVAS_PROVIDER_TYPE |
DataCanvas engine. duckdb enables the SQL surface; set none to disable analytical staging (the dataframe_* tools then report canvas_disabled; faostat_query_observations pages with offset and stages nothing). |
duckdb |
CANVAS_DEFAULT_ROW_LIMIT |
Most rows one faostat_dataframe_query call returns, and the cap its row_limit is served at; below 1000 it is also row_limit's default. |
10000 |
FAOSTAT_DATAFRAME_DROP_ENABLED |
Set true to make faostat_dataframe_drop callable. Off, the tool is registered disabled: absent from tools/list, shown on the landing page with this hint. |
false |
FAOSTAT_CLAMP_LIMITS |
A count input (limit, top_n, row_limit) above its cap is served at the cap, with requestedX/effectiveX fields and a notice. Set false to advertise each cap as a schema maximum and reject larger values. |
true |
MCP_TRANSPORT_TYPE |
Transport: stdio or http. |
stdio |
MCP_SESSION_MODE |
HTTP session mode: stateless, stateful, or auto (resolves to stateful). The server declares stateless in src/index.ts — no tool asks the caller for input mid-handler — and setting this overrides that declaration. |
stateless |
MCP_HTTP_PORT |
Port for the 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 |
See .env.example for the full list of optional overrides.
Running the server
Local development
Requires Bun v1.4.4 or higher (or Node.js v24+), 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 or stale planner statistics
bun run mirror:verify # report sync status, local row counts, checkpoints, and dimension population
mirror: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.
After upgrading an older mirror, run mirror:refresh. Each row records the update date of the file it came from, and rows an older release wrote carry none, so that first refresh re-downloads every synced domain once, even when its upstream date is unchanged. FS and GLE rebuild once to recover period/text-item rows and separate source estimates; they remain unready until that rebuild succeeds. Compatible numeric domains stay readable throughout and gain the new indexes during the refresh. Until those indexes are prepared, domain-wide element/unit discovery can be slow; scope it with item_codes or item_codes_text when possible.
A refresh removes the rows its rebuilt domain file does not carry and prints <N> records applied, <M> removed per domain.
mirror:refresh retries a contended domain with backoff for up to two minutes before starting another attempt. An SQLite operation already in progress can finish its lock wait. If contention persists, the command reports which domains it skipped, refreshes later domains, and exits nonzero.
mirror:refresh also builds query-planner statistics (ANALYZE) when they are missing, stale after a data change, or incomplete for the current indexes. The server checks the persisted state on data reads and can schedule a background build while continuing to answer queries. Reads defer maintenance while a sync or closing statistics build holds the domain lease. If another process publishes fresh statistics, the server reopens its worker connections to pick up the new query plans.
Docker
docker run --rm -p 3010:3010 -v faostat-mirror:/usr/src/app/.faostat-mirror ghcr.io/cyanheads/faostat-mcp-server:latest
Build 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, row counts, checkpoints, and dimension population
docker exec <container> bun run mirror:refresh # re-sync updated domains; build missing or stale planner statistics
Project structure
| Directory | Purpose |
|---|---|
src/index.ts |
createApp() entry point — registers the seven tools (faostat_dataframe_drop behind its opt-in flag), wires the mirror and canvas in setup(), schedules the HTTP refresh. |
src/config |
Server-specific environment variable parsing and validation with Zod. |
skills/faostat-guide |
Published agent guide, also served as an MCP skill resource. |
src/mcp-server/tools/definitions |
Tool definitions (*.tool.ts). |
src/services/faostat-mirror |
Bulk-download mirror, streaming ZIP ingester, and shared dimension store. The two-worker read pool runs cube reads, text search, index preparation on populated cubes, and statistics builds off the main thread. |
src/services/canvas-accessor.ts, canvas-staging.ts |
DataCanvas accessor and the spill/query/describe/drop staging layer. |
scripts/faostat-mirror-*.ts |
mirror:init / mirror:refresh / mirror:verify CLIs. |
tests/ |
Unit and integration tests mirroring src/. |
Development guide
See CLAUDE.md/AGENTS.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 in the
createApp()array insrc/index.ts - Wrap 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 test
License
Apache-2.0 — see LICENSE for details.
Установка @Cyanheads/Faostat Server
У этого сервера нет опубликованного пакета — он собирается из исходников. Открой репозиторий и следуй инструкции в README.
▸ github.com/cyanheads/faostat-mcp-serverFAQ
@Cyanheads/Faostat Server MCP бесплатный?
Да, @Cyanheads/Faostat Server MCP бесплатный — установка в пару кликов через Unyly без оплаты.
Нужен ли API-ключ для @Cyanheads/Faostat Server?
Нет, @Cyanheads/Faostat Server работает без API-ключей и переменных окружения.
@Cyanheads/Faostat Server — hosted или self-hosted?
Self-hosted: сервер запускается локально на твоей машине командой из раздела установки.
Как установить @Cyanheads/Faostat Server в Claude Desktop, Claude Code или Cursor?
Открой @Cyanheads/Faostat Server на unyly.org, выбери вкладку своего клиента (Claude Desktop, Claude Code, Cursor) и нажми Install — конфиг сгенерируется автоматически, без правки JSON.
Похожие MCP
Postgres
Query your database in natural language
автор: Anthropicwenb1n-dev/SmartDB_MCP
Connect to multiple databases at once (MySQL, PostgreSQL, SQL Server, MariaDB, Dameng, Oracle) for operations, health analysis and SQL optimization.
автор: wenb1n-devPostgres Server
This server enables interaction with PostgreSQL databases through the Model Context Protocol, optimized for the AWS Bedrock AgentCore Runtime. It provides tools
автор: madhurprashPostgreSQL
Read-only database access with schema inspection.
автор: modelcontextprotocolRedis
Interact with Redis key-value stores.
автор: modelcontextprotocolSQLite
Database interaction and business intelligence capabilities.
автор: modelcontextprotocolmxcp
Open-source framework for building enterprise-grade MCP servers using just YAML, SQL, and Python, with built-in auth, monitoring, ETL and policy enforcement.
автор: raw-labsjulien040/anyquery
Query apps with SQL from a single local-first binary; also connects to PostgreSQL, MySQL and SQLite-compatible databases.
автор: julien040drakonkat/wizzy-mcp-tmdb
Search and retrieve movie, TV show and person information from The Movie Database (TMDB) API.
автор: drakonkatlongevity-genie/opengenes-mcp
Query the OpenGenes database for aging and longevity research.
автор: longevity-genieCompare @Cyanheads/Faostat Server with
Не уверен что выбрать?
Найди свой стек за 60 секунд
Автор?
Embed-бейдж для README
Похожее
Все в категории data
