FAOSTAT MCP Server
This server turns the full FAOSTAT API into 23 AI-callable MCP tools, letting an assistant discover domains, resolve codes, and pull UN food/agriculture statistics conversationally.
Explore the catalog — list top-level data groups, get the full group→domain tree, list domains in a group, and inspect a domain's available dimensions (area, item, element, year).
Resolve codes safely — browse all filter codes for a dimension, search codes by name (
faostat_search_codesforces the agent to ask you when a term like "production" is ambiguous), and validate region/country/indicator names against FAO definitions.Fetch real statistics —
faostat_get_dataqueries any domain filtered by area/item/element/year or named code sets, withfaostat_get_datasizeto size a query first; supports objects/compact/csv output, field selection, unit/flag/code toggles, and row limits.Rank and compare —
faostat_get_rankingsreturns top-N countries by production, yield, or trade value (e.g. top 10 maize producers in 2022).Read documentation — domain definitions, definition types, full methodology metadata, printable metadata, bulk download listings, and related methodology documents.
Pull reports — fetch structured report data and its column headers via a custom payload.
Authenticate simply —
faostat_setupvalidates and stores credentials once (system keychain or a 600-mode file) for all future sessions;faostat_refresh_tokenrecovers from token expiry, andfaostat_pingchecks API health.Run efficiently — built-in 2 req/s rate limiting, auto-retry with backoff, and a 3-tier cache (in-memory 20 min → SQLite 24 h → optional Redis 30 min), working over stdio with Claude Desktop, Cursor, Windsurf, Zed, or any MCP client.
Provides tools to query the FAOSTAT database of the United Nations Food and Agriculture Organization (FAO), enabling AI assistants to retrieve and analyze global food, agriculture, trade, nutrition, emissions, forestry, and fisheries statistics across 245 countries and territories.
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., "@FAOSTAT MCP Server what was the global wheat production 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.
FAOSTAT MCP Server
Query UN food and agriculture statistics with AI — powered by the Model Context Protocol
An MCP (Model Context Protocol) server that exposes the full FAOSTAT API as tools for AI assistants. Connect any MCP-compatible client — Claude, Cursor, Windsurf, Zed, or your own agent — to the world's most comprehensive database of food, agriculture, fisheries, forestry, and nutrition statistics, covering 245 countries and territories from the United Nations Food and Agriculture Organization (FAO).
Keywords: FAOSTAT, MCP server, Model Context Protocol, AI agriculture data, FAO statistics, food security AI, agricultural data Python, UN data, crop production statistics, Claude, Cursor, Windsurf
Why Use This?
Researchers, data journalists, policy analysts, and developers can ask natural-language questions and get answers directly from FAOSTAT — without writing a single API call. Your AI assistant handles domain discovery, filtering, and interpretation automatically.
Who is this for?
Agricultural economists and food security researchers
Journalists and policy analysts working with FAO data
Developers building AI pipelines on top of FAOSTAT
Anyone who wants to explore crop, trade, nutrition, or emissions data conversationally
Related MCP server: Plantos MCP Server
What is FAOSTAT?
FAOSTAT is the statistical database of the United Nations Food and Agriculture Organization (FAO). It is the world's most comprehensive freely available source of data on food and agriculture, covering:
Crop and livestock production — yields, harvested area, and quantities for hundreds of commodities
Trade — import/export volumes and values between countries
Food security — prevalence of undernourishment, dietary energy supply, and access indicators
Emissions — greenhouse gas emissions from agriculture, land use, and food systems
Forestry and fisheries — production and trade data
Prices, inputs, and population — producer prices, fertilizer use, and demographic context
Data spans from 1961 to the present, across 245 countries and territories, in multiple languages.
What is MCP?
The Model Context Protocol is an open standard that lets AI assistants call external tools at runtime. This server registers all FAOSTAT API endpoints as discoverable tools — your AI assistant automatically selects and chains the right calls when you ask a question.
Features
23 MCP tools covering every FAOSTAT endpoint (data, metadata, rankings, bulk downloads, reports)
245 countries and territories across dozens of domains: crops, livestock, trade, food security, emissions, forestry, fisheries, and more
Built-in rate limiting (2 req/s) — safe for the FAOSTAT production API out of the box
Auto-retry with exponential backoff on transient network errors
Rich tool descriptions so the AI knows exactly when and how to call each tool
3-tier hybrid caching — in-memory (20 min) → SQLite disk (24 h, cross-session) → Redis (optional, 30 min)
Zero-config auth via
faostat_setup— store credentials once, never touch a config file againDisambiguation via
faostat_search_codes— agents ask before guessing ambiguous codesWorks with Claude Desktop, Claude Code, Cursor, Windsurf, Zed, and any MCP-compatible client
Quick Start
Prerequisites
Python 3.10+
Any MCP-compatible client (Claude Desktop, Cursor, Windsurf, Zed, or a custom agent)
Option A — Install via MCP Registry (recommended)
Listed on the official MCP Registry — discoverable directly from Claude Desktop, Cursor, and any MCP-compatible client.
# Install with pip or uvx (no virtual env needed):
pip install faostat-mcp
uvx faostat-mcpUpdating: uvx faostat-mcp picks up new releases when your AI client restarts the server; if you still see an old version, run uvx faostat-mcp@latest once. pip and uv tool install don't upgrade on their own: run pip install -U faostat-mcp or uv tool upgrade faostat-mcp, then restart your client. The server also checks PyPI once per session and logs a notice to stderr when a newer version exists (opt out with FAOSTAT_NO_UPDATE_CHECK=1).
Option B — Install from source
git clone https://github.com/berba-q/faostat-mcp.git
cd faostat-mcp
pip install -e .Configure credentials
Easiest — use the faostat_setup tool (no config files needed):
Once the server is running and connected to your AI client, ask your assistant:
"Call faostat_setup with my FAOSTAT username and password."
The tool validates your credentials against the API, then stores them securely in your system keychain (macOS/Windows) or ~/.config/faostat-mcp/credentials.json (Linux/Docker). All subsequent sessions authenticate automatically — no env vars or .env file required.
Alternative — environment variables (CI/CD, Docker, advanced):
cp .env.example .env
# Edit .env:
# FAOSTAT_USERNAME=your_email ← recommended: tokens refresh automatically
# FAOSTAT_PASSWORD=your_password
# FAOSTAT_API_TOKEN=your_token_here ← alternative: expires after 1 hourRegister for a free FAOSTAT API account at the FAOSTAT Developer Portal.
Optional — Redis caching (multi-user / high-volume deployments)
The server works without Redis (SQLite disk cache is used instead). For shared or high-volume setups, launch Redis via Docker:
docker run -p 6379:6379 -it redis/redis-stack:latestThen set REDIS_HOST_IP_ADDRESS, REDIS_HOST_PORT_NUMBER, and REDIS_DATABASE in .env.
Running the Server
Development mode (interactive MCP Inspector UI)
mcp dev faostat_mcp/server.pyOpens a browser UI at http://localhost:5173 where you can browse and test all 23 tools interactively.
Production mode (stdio transport, for Claude Desktop)
python -m faostat_mcp.server
# or, using the installed script:
faostat-mcpCaching
The server uses a 3-tier cache to minimise redundant API calls. FAOSTAT data updates at most daily, so most repeated queries are served instantly.
Tier | TTL | Scope | Notes |
In-memory | 20 min | Current session | Fastest; reset on server restart |
SQLite disk | 24 h | Cross-session |
|
Redis | 30 min | Multi-user shared | Optional; set |
Cache lookup order: memory → disk → Redis → API call. A disk or Redis hit promotes the value to memory for the rest of the session.
To disable the disk cache (e.g. on a read-only filesystem), set FAOSTAT_DISK_CACHE=false.
MCP Client Integration
The server speaks standard MCP over stdio, so it works with any compatible client.
Recommended config (PyPI install)
{
"mcpServers": {
"faostat": {
"command": "uvx",
"args": ["faostat-mcp"]
}
}
}Dev / source config
{
"mcpServers": {
"faostat": {
"command": "python",
"args": ["-m", "faostat_mcp.server"],
"cwd": "/path/to/faostat-mcp",
"env": {
"FAOSTAT_USERNAME": "your_email",
"FAOSTAT_PASSWORD": "your_password"
}
}
}
}Claude Desktop
Add one of the blocks above to:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
Restart Claude Desktop — faostat will appear in the tools panel.
Cursor
Add the block to .cursor/mcp.json in your project root, or to your global Cursor MCP settings. See the Cursor MCP docs for details.
Windsurf / Zed / other clients
Any client that supports MCP stdio servers accepts the same config shape. Consult your client's documentation for the config file location.
Example Queries
Once connected, ask your AI assistant questions like:
Domain | Example Question |
Crop production | "What were the top 10 wheat-producing countries in 2022?" |
Food security | "Show me food security indicators for Ethiopia from 2015 to 2020" |
Trade | "Which countries are most dependent on food imports?" |
Yield comparison | "Compare maize yields between the USA and Brazil over the last decade" |
Emissions | "What are greenhouse gas emissions from agriculture in Sub-Saharan Africa?" |
Discovery | "What agricultural datasets does FAOSTAT have for trade?" |
Your AI assistant will automatically:
Call
faostat_list_groupsorfaostat_groups_and_domainsto find the right domainCall
faostat_search_codesto look up a code by name — if multiple codes match (e.g. "production" matches both Production and Gross Production Index), the assistant pauses and asks you to choose before proceedingRegions and indicators are checked with
faostat_resolve_name— if no matching FAOSTAT definition is found for your request (e.g. "Global South"), the assistant tells you so and offers the FAO-defined alternatives (e.g. "West Africa" → Western Africa) instead of inventing one
Call
faostat_get_dataorfaostat_get_rankingswith the confirmed codesInterpret and summarize the results in plain language
Available MCP Tools
Discovery & Metadata
Tool | Description |
| Check API health |
| List all data groups |
| Full domain tree |
| Domains within a group |
| Available filters for a domain |
| Browse all country/item/element filter codes |
| Search codes by name — returns |
| Domain definitions |
| Definitions by type within a domain |
| All definition types |
| FAO-wide definitions for one type, no domain needed (regions/ |
| Check a region, country or indicator name against FAO definitions — returns |
| Full domain metadata |
| Printable metadata |
Data Retrieval
Tool | Description |
| Fetch actual statistics |
| Estimate query result size before fetching |
| Top-N country rankings |
| Report data |
| Report column headers |
| Bulk download file listing |
| Related documents |
Authentication
Tool | Description |
| First-time setup — validate and store credentials securely; subsequent sessions authenticate automatically |
| Manually refresh the API access token |
Project Structure
faostat-mcp/
├── pyproject.toml
├── smithery.yaml ← Smithery MCP registry manifest
├── .env.example
├── mcp_config_example.json ← AI config snippet
└── faostat_mcp/
├── server.py ← FastMCP server + all 23 tool definitions
└── client.py ← HTTP client, rate limiting, 3-tier cache, credential storageImportant: Filter Codes vs Display Codes
The FAOSTAT API uses two different code systems: filter codes (used in query parameters) and display codes (shown in response data and bulk CSVs). Always use filter codes from faostat_get_codes when calling faostat_get_data.
Area, item, and year codes are the same for both. Only element codes differ:
QCL — Crops and Livestock Products
Filter Code | Display Code | Element |
|
| Area harvested |
|
| Yield |
|
| Production quantity |
|
| Stocks |
|
| Producing animals / slaughtered |
TM — Trade Matrix
Filter Code | Display Code | Element |
| — | Import quantity |
| — | Import value |
| — | Export quantity |
| — | Export value |
FS — Food Security
Filter Code | Display Code | Element |
| — | Value |
| — | Confidence interval |
Always call
faostat_get_codes(dimension_id='element', domain_code=...)before querying data. Filter codes vary by domain and cannot be inferred from display codes.
# WRONG — uses display code 5510, returns empty data
faostat_get_data('QCL', area='2', item='515', element='5510', year='2024')
# CORRECT — uses filter code 2510, returns data
faostat_get_data('QCL', area='2', item='515', element='2510', year='2024')Limitations & Notes
This server targets the FAOSTAT production API (
https://faostatservices.fao.org/api/v1).Rate limit: 2 requests/second, enforced automatically via token bucket.
Responses are cached across 3 tiers (memory → SQLite disk → Redis) to reduce API calls — see
.env.examplefor TTL and size configuration.The SQLite disk cache lives at
~/.cache/faostat-mcp/cache.dband defaults to 24 h TTL with a 1,000-entry LRU cap. SetFAOSTAT_DISK_CACHE=falseto disable.For large domains (e.g., Trade Matrix), always apply area, item, and year filters to keep response sizes manageable.
Skills
Want guided analysis workflows on top of this server? Check out FAOSTAT Skills — 9 platform-agnostic AI skills for country profiles, commodity briefings, trade analysis, climate assessments, data visualization, and more. Works with Claude Code, OpenAI Codex, and any AI assistant that supports the SKILL.md format.
Related Projects & Resources
FAOSTAT Skills — analysis skills built on top of this MCP server
Model Context Protocol — the open standard powering this server
FAOSTAT — UN FAO's official statistics portal
FAOSTAT API Docs — developer reference
Claude Desktop — one of the AI assistants this server works with
Cursor — AI code editor with MCP support
Windsurf — AI IDE with MCP support
Contributors
Thanks to everyone who has contributed to this project.
Contributor | Contribution |
Project author — API client, MCP tool layer, response formatting | |
Hybrid caching — in-memory (dict + min-heap TTL) and Redis tiers with graceful fallback |
Contributions are welcome — see CONTRIBUTING.md for guidelines.
Citation
If you use this tool in academic work or research, please cite it:
Plain text:
Obli-Laryea, G., & Contributors. (2026). FAOSTAT MCP Server: AI-assisted access to FAOSTAT (v1.2.2) [Computer software]. https://github.com/berba-q/faostat-mcp
BibTeX:
@software{faostat_mcp,
author = {Obli-Laryea, Griffiths and {Contributors}},
title = {FAOSTAT MCP Server: AI-assisted access to UN food and agriculture statistics},
year = {2026},
url = {https://github.com/berba-q/faostat-mcp},
version = {1.2.2}
}See the Contributors section for a full list of authors.
When citing the underlying FAOSTAT data, use the FAO's recommended format with the specific domain:
FAO, {year}. FAOSTAT: {Domain Name}, http://www.fao.org/faostat/en/#data/{domain_code}
For example:
FAO, 2026. FAOSTAT: Crops and Livestock Products, http://www.fao.org/faostat/en/#data/QCL
FAO, 2026. FAOSTAT: Emissions Totals, http://www.fao.org/faostat/en/#data/GT
Changelog
See CHANGELOG.md for a full history of changes, generated automatically from conventional commits.
GitHub Topics
If you fork or star this repo, suggested topics: mcp, faostat, model-context-protocol, ai-tools, agriculture, food-security, fao, un-data, python, llm, unfao, undata
Smaller tool responses
Data, rankings, and global definitions default to response_format="compact" (column names once, followed by row arrays). Use response_format="objects" for the previous object-per-row shape, or "csv" for data and rankings. Select fields on data queries while preserving units needed to interpret values. Search results default to 25 matches; narrow the query if _truncated is true.
When the domain is known, use faostat_search_codes directly. The global name resolver returns definition_code, which is not necessarily a query filter code. A no_matching_definition result describes this lookup, not all FAO terminology. Code browsing, search, and validation share a cached table; repeated data queries reuse raw responses across formats, field selections, and row limits.
Available Tools
23 toolsfaostat_definition_typesA
List all available definition types (used with faostat_get_definition_type for FAO-wide definitions, or faostat_get_definitions_by_type within one domain).
Inputs: lang. Returns: result
faostat_get_codesA
Browse domain FILTER codes. Prefer faostat_search_codes for named lookups. Element filter codes differ from display codes (QCL: Production filter 2510, display 5510). limit=0 returns all codes.
Inputs: domain_code (required), dimension_id (required), lang, limit. Returns: result
faostat_get_dataA
Fetch domain data. Resolve filter codes with faostat_search_codes first. Element FILTER codes differ from display codes (QCL Production: filter 2510, display 5510). Filter large queries by area/item/year; check datasize when unsure. Prefer response_format="compact" and fields to save tokens; objects and csv are supported. limit=50; 0 returns all rows. Preserve units when selecting fields.
Inputs: domain_code (required), area, item, lang, +13 more. Returns: result
faostat_get_datasizeA
Estimate the number of rows a data query will return BEFORE fetching. Use this to check if a query is too large before calling faostat_get_data. Accepts the same filter parameters as faostat_get_data.
Inputs: domain_code (required), area, item, lang, +6 more. Returns: result
faostat_get_definitionsB
Get all definitions (descriptions of items, elements, flags) for a domain.
Inputs: domain_code (required), lang. Returns: result
faostat_get_definitions_by_typeC
Get definitions for a domain filtered by type (e.g. items, elements, flags).
Inputs: domain_code (required), definition_type (required), lang. Returns: result
faostat_get_definition_typeA
Get FAOSTAT-wide definitions without a domain. Types include areagroup, area, indicator, element, item, unit, flag; use faostat_definition_types for all types. search filters text columns; limit=100, 0 returns all. response_format: compact (default) or objects. Definition codes are not necessarily query filter codes.
Inputs: definition_type (required), lang, limit, search, +1 more. Returns: result
faostat_get_dimensionsB
Get the structure of a domain — what dimensions (filters) are available, such as area (country), item (commodity), element (measure), and year.
Inputs: domain_code (required), lang. Returns: result
faostat_get_metadataB
Get full methodology and metadata for a domain — including data sources, collection methods, coverage, and limitations.
Inputs: domain_code (required), lang. Returns: result
faostat_get_metadata_printC
Get metadata for a domain in a printable/simplified format.
Inputs: domain_code (required), lang. Returns: result
faostat_get_rankingsB
Rank countries by a domain item/element/year. element_code is a DISPLAY code (QCL Production: 5510), unlike get_data filter code 2510. limit=10. response_format defaults to compact; objects and csv are supported.
Inputs: year (required), item_code (required), domain_code (required), element_code (required), +3 more. Returns: result
faostat_get_report_dataC
Get structured report data from FAOSTAT.
Inputs: payload (required), lang. Returns: result
faostat_get_report_headersC
Get the column headers/schema for a report before fetching its data.
Inputs: payload (required), lang. Returns: result
faostat_groups_and_domainsB
Get the full hierarchical tree of all FAOSTAT groups and their domains. Use this for a complete overview of all available datasets.
Inputs: lang. Returns: result
faostat_list_bulk_downloadsB
List available bulk download files for a domain (ZIP/CSV archives). These contain the full domain dataset and can be very large.
Inputs: domain_code (required), lang. Returns: result
faostat_list_documentsC
List related documents (methodology papers, questionnaires) for a domain.
Inputs: domain_code (required), lang. Returns: result
faostat_list_domainsC
List all datasets (domains) within a FAOSTAT group.
Inputs: group_code (required), lang. Returns: result
faostat_list_groupsB
List all top-level FAOSTAT data groups (e.g. Production, Trade, Food Security). Use this to discover what categories of data are available.
Inputs: lang. Returns: result
faostat_pingA
Check the FAOSTAT API health status. Returns a status message indicating if the API is online.
Inputs: no named parameters. Returns: result
faostat_refresh_tokenA
Force-refresh the FAOSTAT API authentication token.
Inputs: no named parameters. Returns: result
faostat_resolve_nameA
Find FAOSTAT definitions by name when the domain is unknown. kind: region, country, indicator (includes elements/items). definition_code identifies a definition, NOT a domain query filter; use faostat_search_codes for query codes. Exact matches are defined; partial matches require confirmation. no_matching_definition means this lookup found no match, not proof FAO never defines the concept. Narrow truncated matches. Custom constructions require explicit user request and a non-FAO label.
Inputs: kind (required), name (required), lang. Returns: result
faostat_search_codesA
Find domain FILTER codes by name (case-insensitive substring). Use before querying unknown codes. A unique match is usable; multiple matches require user selection. Default limit=25; narrow the query when truncated. query must be nonblank.
Inputs: query (required), domain_code (required), dimension_id (required), lang, +1 more. Returns: result
faostat_setupA
Validate and persist FAOSTAT credentials for automatic authentication across sessions. username is the account email. Saves to the system keychain when available and ~/.config/faostat-mcp/credentials.json (mode 600).
Inputs: password (required), username (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 23 tools
Several tools overlap heavily in discovery and lookup roles: faostat_get_definitions, faostat_get_definitions_by_type, faostat_get_definition_type, faostat_definition_types, faostat_get_codes, and faostat_search_codes all deal with codes or definitions, requiring careful attention to subtle distinctions. The descriptions do differentiate filter codes from display codes and definition codes from query codes, which helps, but the set remains easy to misselect.
Almost all tools use the faostat_ prefix with snake_case and a verb_noun pattern such as faostat_get_data, faostat_list_domains, and faostat_search_codes. The main deviations are noun-phrase names like faostat_definition_types, faostat_groups_and_domains, and faostat_ping, plus inconsistency between faostat_get_definition_type and faostat_definition_types.
At 23 tools, the set is on the heavy side for a data-access server. The domain is complex enough to justify many tools, but authentication, discovery, code lookup, definitions, metadata, and reporting could likely be consolidated, making this borderline rather than well-scoped.
The surface covers authentication, group/domain discovery, code lookup, definitions, metadata, data retrieval, rankings, reports, and bulk-download discovery. Minor gaps remain, such as no actual bulk-download retrieval tool and no obvious report-discovery tool beyond fetching headers or data.
Maintenance
Related MCP Connectors
Official statistics for AI agents: Eurostat, World Bank, OECD, IMF and WHO data for 150+ countries.
UN FAOSTAT global food & agriculture statistics over a local SQLite mirror, via MCP.
Official economic statistics for AI agents: GDP, inflation, trade and debt for 150+ countries.
Nutrition data for AI agents and LLMs, powered by Edamam’s database of 1,000,000 foods, including 680,000+ with UPC codes. Lookup via natural language and barcode at low cost and low latency. Highly accurate, deterministic data covering macro and micronutrients, allergens, and lifestyle diet tags.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceEnables plain English queries about US agricultural data, including historical crop statistics from NASS QuickStats and current cash grain prices from AMS Market News.-

Plantos MCP Serverofficial
AlicenseNot gradedqualityFmaintenanceEnables AI assistants to analyze farm locations, retrieve soil and weather data, access commodity market prices, and chat with an agricultural advisor for farming recommendations.MIT- FlicenseAqualityCmaintenanceEnables access to USDA NASS agricultural statistics data through natural language queries, supporting full dataset retrieval, record counts, and parameter discovery.34-
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to access free, open agronomic data for field briefings, spray windows, water balance, pest pressure, and more, using only public data sources without API keys.1MIT