xippios-mcp
Read-only MCP server exposing USDA NASS, USDA PSD, and UN Comtrade agricultural and trade data tools.
USDA NASS Quick Stats: query acreage, production/yield and in-season forecasts, county production/yield, crop progress and condition, grain stocks, livestock inventories, milk production, prices received, census farm counts, generic filtered data, and parameter value lists.
USDA PSD: retrieve country balance sheets, world and all-country supply/distribution data, multi-year time series, top producing/exporting countries, latest release info and release dates, plus reference lists for commodities, attributes, countries, regions, and units.
UN Comtrade: fetch or count trade records, compare bilateral and mirror flows, build commodity time series, rank top partners, get world trade and world share, compute trade balance, check data availability and metadata, list releases/live updates, and search classifications, reporters, partners, and codes.
Query support: built-in count-before-fetch guards, optional year splitting, result caps/previews for large answers, code validation with closest-match errors, and searchable reference lists to help form valid queries.
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., "@xippios-mcp Get USDA NASS corn yields for Iowa from 2020 to 2024."
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.
xippios-mcp
The self-hosted MCP host of the xippios SDK family. It serves the MCP tools of the family's packages from one process, by endpoint and group: an endpoint mounts a package's own server, read or write, and a group combines several packages' tools on one endpoint, never read and write tools together. It runs on stdio locally and on streamable HTTP on a server, each endpoint with its own auth, a bearer token by default; the secrets stay in the environment, never in the config file.
xippios-mcp --config <path> checks a config, builds every endpoint's server and lists
the endpoints; --stdio <endpoint> serves one endpoint on stdio, and --http serves
every endpoint over streamable HTTP, each with its bearer (see Serving). A Docker image,
built from this repository, serves them from a container (see Docker).
Install
uv add "xippios-mcp[all]" # the host with every package below
uv add "xippios-mcp[usda-nass]" # or one extra per package you serveRelated MCP server: mcp-gate
Packages
Each package is an extra with a lower bound only, so the host installs every package at its latest release.
Extra | Distribution | Lower bound | Servers | Tools |
|
|
| read and write | 24 read, 11 write |
|
|
| read | 19 |
|
|
| read | 13 |
|
|
| read | 7 |
|
|
| read | 9 |
|
|
| read | 10 |
|
|
| read | 20 |
|
|
| read | 16 |
|
|
| read | 12 |
The tools are each package's tasks.__all__ (tasks_write.__all__ for a write server)
less its BULK_TASKS, which are Python-only, counted at the version of the lower bound;
a later release may add tools. all installs the nine. xippios-usda-wasde joins
later: its 0.1.1 needs xippios-usda-esmis below 0.2.
The ceilings of usda-nass and usda-gats
--split-years of xippios-usda-nass-mcp and --series-months of
xippios-usda-gats-mcp are options of those packages' own entry points, which the host
does not run. The host therefore serves the ceilings the packages keep in Python: a
split usda_nass_get_data spans up to 20 years, at up to two keyed calls a year (the
entry point's default is 5 years), and usda_gats_get_census_export_series,
usda_gats_get_census_import_series and usda_gats_get_census_reexport_series span up
to 60 months, at one call a month (the entry point's default is 24 months). An operator
who wants fewer calls per tool call leaves those tools out with an endpoint's exclude
list (see Configuration).
Configuration
The host reads one TOML file that names its endpoints. Each [endpoints.<name>] table
is one endpoint, which the HTTP transport serves at /<name>/mcp:
[endpoints.agriculture] # served at /agriculture/mcp
packages = ["usda-nass", "usda-psd", "comtrade"]
exclude = { usda-nass = ["get_counts"] } # or include = { ... }; exact task names
auth = "bearer" # the default; or "none"
token_env = "XIPPIOS_MCP_AGRICULTURE_TOKEN" # a name ending in _TOKEN, never a value
allow_remote = false # the default
[endpoints.accounting-write]
packages = ["cashctrl:write"]
auth = "none"An endpoint that names one package and no list serves that package's own server, as the package builds it:
xippios.<package>.mcp.server, ormcp_write.serverfor<slug>:write, with its instructions and result caps.A group, several packages, or an endpoint with an
includeorexcludelist is a server the host builds, namedxippios-<endpoint>: each package's tools under their own names (usda_nass_get_data), with the package's result caps for the tools it keeps.Read and write never mix: an endpoint's packages are all
<slug>:writeor none, and the host refuses a group that mixes them.includeandexcludeare keyed by package slug and name exact task names, a task function's__name__(get_counts, notusda_nass_get_counts); a package takes one of the two, and an empty list is refused. A name that is no tool of the package is refused, a task in the package'sBULK_TASKSamong them, since a bulk task is Python-only and no tool.authis"bearer"by default, or"none". With the bearer,token_envnames the environment variable that holds the token, a name ending in_TOKEN(XIPPIOS_MCP_<ENDPOINT>_TOKEN), and the token itself stays in the environment, never in the file. The host reads the variable once, when--httpstarts, and never on stdio or when it lists.allow_remoteisfalseby default; it lets anauth = "none"write endpoint beyond loopback (see The loopback rule).An optional
[http]table names theHostandOriginvalues the HTTP transport accepts behind a reverse proxy (see Behind a reverse proxy).
Check a config before serving it:
xippios-mcp --config host.tomlIt loads the file, builds every endpoint and prints one line per endpoint; for
docs/host.example.toml,
the sample above, with the packages at the lower bounds:
agriculture: read, 46 tools of usda-nass, usda-psd, comtrade
accounting-write: write, 11 tools of cashctrlA key, package or task the host refuses stops it with exit status 2 and a message that
names the file, the endpoint and the key. The list runs neither the mounted-once check
nor the loopback check of Serving, which need --http and its --host.
A server the host builds carries none of the packages' own instructions: its
instructions are one sentence naming its packages and their tool counts. No endpoint
takes a package's command-line options, such as cashctrl's --org lock or the ceilings
above, since the host runs no package's entry point. The package contract of the next
template release gives the host what it needs to carry them, from the host's first minor
after that release and xippios-core 0.4.0.
Serving
stdio
xippios-mcp --config host.toml --stdio agricultureserves the one endpoint agriculture on stdio, for an MCP client that starts the host
as its own process. stdio has no auth: the host reads no token variable, and an
endpoint's auth, token_env and allow_remote apply to HTTP only. In Claude Code:
claude mcp add agriculture -- xippios-mcp --config host.toml --stdio agriculturewith the config's absolute path in place of host.toml when Claude Code runs in another
directory.
Streamable HTTP
xippios-mcp --config host.toml --http --host 127.0.0.1 --port 8000serves every endpoint of the config from one process, each at
http://127.0.0.1:8000/<name>/mcp: http://127.0.0.1:8000/agriculture/mcp for the
sample. --host defaults to 127.0.0.1 and --port to 8000; both need --http, and
--http and --stdio exclude each other. Before it serves, the host reads each bearer
endpoint's token and applies the checks below; a refusal exits with status 2 and serves
nothing. A package's own server serves one HTTP endpoint: two endpoints that each name
usda-nass alone are refused, and an include or exclude list on one of them makes
its server one the host builds.
The bearer
An endpoint with auth = "bearer" answers a request without the token with 401 and
WWW-Authenticate: Bearer realm="xippios-mcp", and one with a wrong token with
error="invalid_token" added; such a request never reaches the endpoint. The token is
the value of the variable token_env names, read once when --http starts: an unset or
empty variable stops the host with exit status 2, and so does a value with leading or
trailing whitespace, which no token a client sends can match. The host keeps the token's
SHA-256 digest only, compares in constant time, and never logs the token or the
Authorization header. A random token will do, openssl rand -hex 32 for instance, set
in the environment of the host and of the client.
In Claude Code:
claude mcp add --transport http agriculture http://127.0.0.1:8000/agriculture/mcp \
--header 'Authorization: Bearer ${XIPPIOS_MCP_AGRICULTURE_TOKEN}'In single quotes the shell passes ${XIPPIOS_MCP_AGRICULTURE_TOKEN} on as written, and
Claude Code expands it from its own environment when it connects, so the token stays out
of Claude Code's config; in double quotes the shell would write the token itself into
the config. Claude Code reads some well-known credential variables as empty in a remote
server's headers (its own, a cloud provider's, others such as NPM_TOKEN); a name of
the operator's own, such as XIPPIOS_MCP_AGRICULTURE_TOKEN, is outside that set and
expands as written. When a token does not arrive, claude --debug-file <file> logs
never expanded toward a remote server for a covered name.
The bearer does not serve claude.ai. claude.ai signs in with OAuth: it starts on a 401
that names a resource_metadata document, and it needs an OAuth authorization server.
The host advertises no resource_metadata and is no authorization server, so
claude.ai needs one in front of the host, which 0.1.0 leaves out (sdk-core ADR-0026,
decision 10).
The loopback rule
An endpoint with auth = "none" that serves a write server, cashctrl:write for
instance, carries no authentication, so --http serves it on a loopback --host only,
127.0.0.1, localhost or ::1, as a package's own entry point keeps its write server
(sdk-core ADR-0014, decision 9). On another --host the host refuses to start unless
the endpoint sets allow_remote = true, and then a gateway in front of it has to
authenticate. A read endpoint with auth = "none", and every bearer endpoint, is served
on any host.
A read server that its package holds to loopback, as sdk-google-mail holds its own, is
not held there by the host's 0.1.0: the packages' loopback-only option is planned for
xippios-core 0.4.0, for the host to read from its first minor after that release and
the next template release. None of the nine packages 0.1.0 serves holds a read server to
loopback, so the case cannot arise before a package that does joins, sdk-google-mail
once it has a release and an extra.
Until the host reads the option, keep an auth = "none" endpoint of such a package on a
loopback --host, or give it the bearer.
Behind a reverse proxy
On a loopback --host the mcp SDK checks the Host and Origin headers itself and
accepts loopback values only, which keeps a web page from reaching the host through DNS
rebinding. Beyond loopback it checks neither, unless the config names what to accept:
[http]
allowed_hosts = ["mcp.example.com"] # the Host values the proxy forwards
allowed_origins = ["https://mcp.example.com"] # browser origins, if anyThe lists replace the SDK's loopback default for every endpoint: a request whose Host
is not listed gets 421, and one with an Origin that is not listed gets 403; a
request without Origin passes. "<host>:*" accepts any port, so add "127.0.0.1:*"
to keep clients that connect directly. Both keys are optional, but allowed_origins
needs allowed_hosts. Without the table, a host bound beyond loopback gets no Host
check.
Docker
The repository builds an image of the host with every package of all, at the versions
uv.lock pins, the set the tests run against. 0.1.0 publishes no image to a registry:
build it from a checkout.
docker build -t xippios-mcp .The image runs xippios-mcp --config /etc/xippios-mcp/host.toml --http --host 0.0.0.0 --port 8000 as the non-root user xippios (uid 10001), and holds no config, key or
token. The operator mounts the config, a file that user can read, and passes every
token by its variable's name, so the value comes from the operator's environment and
stays out of the command line. For a config with one bearer endpoint:
[endpoints.agriculture]
packages = ["usda-nass", "usda-psd", "comtrade"]
auth = "bearer"
token_env = "XIPPIOS_MCP_AGRICULTURE_TOKEN"docker run --rm -p 8000:8000 \
-v "$PWD/host.toml:/etc/xippios-mcp/host.toml:ro" \
-e XIPPIOS_MCP_AGRICULTURE_TOKEN \
xippios-mcpserves it at http://127.0.0.1:8000/agriculture/mcp. The variables the packages read
themselves, their keys among them, are passed the same way, by name; each package's
README names its own. Arguments after the image name replace the image's own, so
docker run --rm -v "$PWD/host.toml:/etc/xippios-mcp/host.toml:ro" xippios-mcp \
--config /etc/xippios-mcp/host.tomlchecks the mounted config and lists its endpoints without serving them.
Inside the container the host binds 0.0.0.0, beyond loopback, so every endpoint is
remote, whichever interface -p publishes the port on: give every endpoint the bearer.
An auth = "none" write endpoint is refused there unless it sets allow_remote = true
(see The loopback rule), and then nothing authenticates it but a gateway in front;
prefer the bearer. Beyond loopback the mcp SDK checks no Host or Origin header, so
behind a reverse proxy the config's [http] table names the values to accept (see
Behind a reverse proxy).
Documents
sdk-core: docs/conventions.md — the conventions of the xippios packages: their layout, names, results, tests and releases, which bind the host as far as sdk-core ADR-0026 says.
sdk-core: docs/adr.md — the index of the family's architecture decisions, which the conventions cite.
sdk-core: docs/definition-of-done.md — what a change satisfies before its pull request is opened.
sdk-core: docs/review-checklist.md — what the review of a pull request checks, in order.
sdk-core: docs/adr/0026-the-host-xippios-mcp.md — the host's design decisions, and in decision 1 which of the conventions bind a package that is no source.
xippios-mcp: docs/adr.md — the index of this package's own decisions, generated from the records in
docs/adr/.
Licence
Apache-2.0. See LICENSE.
Available Tools
46 toolscomtrade_get_bilateral_dataARead-onlyIdempotent
Compare a reporter's trade figures with its partners' mirror figures, row by row.
Upstream's getBilateralData, which its spec marks "EXPERIMENTAL - USE SPARINGLY":
one keyed call, "basic trade data joined with mirror partner data", useful to analyse
bilateral trade asymmetries. Its result is not a list, nor is get_mirror_flows':
data is a BilateralData holding upstream's note, its
timestamp_requested and the rows, data.data, because the note qualifies the
mirror values. It counts the partners with a data gap and gives their share of world
trade without naming them ("a data gap for 2 partner(s) ... approximately 0.015% of the
accumulated world's share").
Each row, a BilateralDataRecord, is one reporter, partner, product code, flow and
period at the total of every breakdown (customs_code "C00", mot_code 0): the
reporter's figures (primary_value, qty, net_wgt, ...) beside the mirror
(mirror_primary_value, mirror_qty, ...), for a reporter's exports "the import
data reported by" its partners, as UN Comtrade's Help Center puts it. It warns that "the
outcome of the mirror data depends on the availability of other reporters rather than
no-trade": a mirror of 0 is no evidence of no trade. For Switzerland's 2023 exports
Afghanistan's mirror of 0 showed which partner the gap was, inferred from the counts
(DPRK alone: 1, the USA alone: none, the three together: 2), not stated. That is no
general rule: the note speaks of a gap "during specific periods" and says "the
calculation of mirror data may be incomplete", and a mirror of 0 can also be a partner
that reported no such imports. primary_value_disc is upstream's, its meaning not
stated; in every recorded row it equals (mirror_primary_value - primary_value) / primary_value, a relative difference (-0.16 for Switzerland's 2023 exports to the
USA, -1.0 where the mirror is 0). The mirror2_* fields are not described
upstream and were None or 0 in every recorded row. A pair upstream holds nothing for
has no row. meta.total is upstream's count. Over MCP the rows are not cut to the
result cap one by one: an answer above it (about 40 rows) comes as a preview of its
text, so name a few partners or periods per call. The query must name reporter_code
or partner_code, and cmd_code: upstream offers no count to check a query's size
before the call (it ignores countOnly), so a broader query is refused before it is
sent. Arguments are checked before the call; an unknown reporter or partner code raises
UnknownCode, an InvalidRequestError naming the packaged list and the closest
area, another mistake InvalidRequestError naming the closest valid value.
Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
cl_code: Product classification, checked against the package's list: "HS"
(all HS editions as reported, the one recorded here; rows name the edition in
classification_code, e.g. "H6"), an edition "H0" to "H6",
SITC "SS", "S1" to "S4", BEC "B4", "B5", "BE",
"TM", for services EBOPS "EB", "EB02", "EB10", "EB10S".
The Tools spec lists HS, S1 to S4, BE4, BE5, EB,
EB02, EB10 and EBSDMX; BE4, BE5 and EBSDMX are not in
the package's list (upstream refused BE5 on data/v1/get and
EBSDMX on getDa) and are refused before the call.
reporter_code: Reporting areas as UN Comtrade's numeric codes, comma-separated,
e.g. "757" Switzerland, "842" USA, "276" Germany, "156" China,
"757,842", as list_reporters lists them. Some differ from ISO numeric
codes: Switzerland is 757, not 756. Required unless partner_code is given.
period: Years "2023" (annual) or months "202305" (monthly),
comma-separated, e.g. "2021,2022,2023"; unlike get_data, more than 12
are accepted (13 answered 13 rows).
partner_code: Partner areas, comma-separated, as list_partners lists them:
"842" USA, "276" Germany, "842,276", one row each. Required
unless reporter_code is given.
cmd_code: Product codes of cl_code, comma-separated, as
list_commodities(cl_code) lists them: "TOTAL" for all goods,
"AG2" for every chapter, codes such as "27", "0901" or
"090111", wildcards such as "27??".
flow_code: One trade flow: "X" exports or "M" imports; upstream refuses
both in one call ("M,X"), so call once per flow.
include_desc: Upstream's includeDesc, sent on as given: the recorded answers
carry no descriptions with or without it (the *_iso and *_desc fields
stay None); list_reporters and list_partners name the codes.
Inputs: cl_code (required), freq_code (required), type_code (required), period, +5 more.
comtrade_get_bilateral_flowsARead-onlyIdempotent
Trade between one reporter and one partner, one row per product code and period.
One data/v1/get call for goods (typeCode C), pinned to the total of every
breakdown (partner2Code 0, customsCode C00, motCode 0, breakdownMode
classic) and with descriptions (includeDesc), so each row is UN Comtrade's figure
for the reporter's side of the trade in one product code and period. At TOTAL
and chapter level these are mostly UNSD aggregates (is_aggregate true,
is_reported false) with no quantity (qty 0, qty_unit_abbr "N/A",
net_wgt 0 or None): read the trade values. Rows are TradeFlowRecord,
sorted by period, then product code; a code or period upstream holds nothing for has
no row. Bounded by construction at product codes times periods rows (at most 12
periods), so there is no count call; a bound above 100,000 raises QueryTooLarge
before the call. Arguments are resolved and checked before the call; an unknown area
raises UnknownCode, an InvalidRequestError naming the packaged list and the
closest area, another mistake InvalidRequestError naming the closest valid value.
meta.request holds the get_data arguments that were sent, codes resolved.
Args:
reporter: The reporting area, as UN Comtrade's code or its ISO alpha-3 code:
"757" or "CHE" Switzerland, "842" or "USA", "276" or "DEU"
Germany, "156" or "CHN" China; list_reporters(search=...) finds them.
Codes are UN Comtrade's, not ISO numeric (Switzerland is 757, not 756). An
alpha-3 code that several codes share resolves to the one still in use
("DEU" is 276, not 280 Fed. Rep. of Germany until 1990).
partner: The partner area, as code or ISO alpha-3 code: "842" or "USA"
(842, the code the USA reports under, not 840), "276" or "DEU", "0"
or "W00" World, the total over all partners; list_partners(search=...)
finds them.
commodities: Product codes of cl_code, comma-separated, each naming one code:
"TOTAL" all goods, an HS chapter "27", heading "2709" or subheading
"270900", e.g. "TOTAL,27". Levels such as "AG2" and wildcards such
as "27??" are for get_data. list_commodities("HS", search="crude")
finds codes.
periods: Years "2022,2023" (annual data) or months "202301,202302" (monthly
data), comma-separated, at most 12, one format: the format sets freqCode.
flow: One trade flow: "X" exports, "M" imports, "RX" re-exports,
"RM" re-imports.
cl_code: Product classification, "HS" by default: all HS editions as each
reporter reported them (rows name the edition in classification_code, e.g.
"H6"); an edition "H0" to "H5", SITC "SS" or "S1" to "S4",
BEC "B4", "B5" also work. "H6" is valid but upstream answered HTTP 500
to every try on 2026-10-23, so "HS" stays the default. EBOPS "EB",
"EB02", "EB10", "EB10S" (services), "BE" and "TM" are
accepted but untested with the pinned typeCode C.
Inputs: flow (required), partner (required), periods (required), reporter (required), +2 more.
comtrade_get_commodity_seriesARead-onlyIdempotent
A reporter's trade in one product with the World over many periods, oldest first.
data/v1/get for goods (typeCode C) with partner 0, World (the total over all
partners), pinned to the total of every breakdown (partner2Code 0, customsCode
C00, motCode 0, breakdownMode classic), with descriptions (includeDesc).
Upstream takes at most 12 periods per call, so the periods are sent in chunks of 12,
one call after the other in the order given (14 periods: two calls, 1.5 s apart), and
the rows are joined and sorted by period; a period upstream holds nothing for has no
row. A period the reporter has not released yet has no row either, which cannot be
told from a period without trade; get_data_availability names the periods a
reporter has released. One row per period at most, so there is no count call. Every
chunk is a keyed call and a free key allows 500 calls a day, so one series takes at
most 120 periods (ten calls); more raise InvalidRequestError before any call:
split the series. Arguments are resolved and checked before any call; an unknown
reporter raises UnknownCode, an InvalidRequestError naming the packaged list
and the closest area, another mistake InvalidRequestError naming the closest valid
value. meta.request holds the get_data arguments with every period; they were
sent 12 at a time.
Args:
reporter: The reporting area, as UN Comtrade's code or its ISO alpha-3 code:
"757" or "CHE" Switzerland, "842" or "USA", "276" or "DEU"
Germany, "156" or "CHN" China; list_reporters(search=...) finds them.
Codes are UN Comtrade's, not ISO numeric (Switzerland is 757, not 756). An
alpha-3 code that several codes share resolves to the one still in use
("DEU" is 276, not 280 Fed. Rep. of Germany until 1990).
commodity: One product code of cl_code: "TOTAL" all goods, an HS chapter
"27", heading "0901" or subheading "090111".
list_commodities("HS", search="coffee") finds codes.
flow: One trade flow: "X" exports, "M" imports, "RX" re-exports,
"RM" re-imports.
periods: Years (annual data) or months (monthly data), comma-separated, one
format, each once, at most 120: "2018,2019,2020,2021,2022,2023",
"202201,202202,202203"; every year from 2010 to 2023 is 14 periods, two
calls.
cl_code: Product classification, "HS" by default: all HS editions as each
reporter reported them (rows name the edition in classification_code, e.g.
"H6"); an edition "H0" to "H5", SITC "SS" or "S1" to "S4",
BEC "B4", "B5" also work. "H6" is valid but upstream answered HTTP 500
to every try on 2026-10-23, so "HS" stays the default. EBOPS "EB",
"EB02", "EB10", "EB10S" (services), "BE" and "TM" are
accepted but untested with the pinned typeCode C.
Inputs: flow (required), periods (required), reporter (required), commodity (required), +1 more.
comtrade_get_comtrade_releasesARead-onlyIdempotent
List UN Comtrade's recent data releases: which reporter's dataset came out when.
Upstream's public getComtradeReleases, "the list of the recent releases, the same
with the UI live update page" (https://comtradeplus.un.org/RecentReleases); the spec
calls each row "A recent or upcoming dataset release". Keyless: no key is sent and no
daily quota is spent, but the call shares the client's pace (the Public tier allows 1
call per second) and its quota policy, so once upstream has said the key's daily quota
is spent it is held back too; the Public tier's preview API's 500 records a call is far
above the rows recorded. One row per release: reporter_code (UN Comtrade's code,
e.g. 757 Switzerland), dataset_desc (e.g. "Switzerland CM 202601"),
flag_code and nr, whose meanings upstream does not state (recorded: two letters,
"CH" for 757; "N" or "R"), and date_release, a naive datetime: upstream
prints it without a UTC offset and states no zone, so none is attached. When recorded on
2026-10-28 it listed 38 releases from 2026-10-22 to 2026-10-28, newest first, every one
at midnight, none in the future; the spec states no order. UN Comtrade keeps one version
of each dataset, so a revised release replaces the earlier data, which is not archived.
meta.total is upstream's count; meta.published_at stays None, since each row
has its own date. No arguments, one call; get_data_availability gives a dataset's
first and latest release.
Inputs: no named parameters.
comtrade_get_countsARead-onlyIdempotent
Count the UN Comtrade trade records a query would return, without fetching them.
The same request as get_data with upstream's countOnly. One call returns at
most 100,000 records, so count first and split a larger query. A count of 0 means no
data matches: an unreported period, a code that is not a reporter, a flow the
reporter does not record. Every count costs one call of the key's daily quota (500
on a free key). Arguments are checked before the call, reporter, partner, customs and
transport codes against the packaged lists: an unknown one raises UnknownCode, an
InvalidRequestError naming the packaged list, its fetch date and the closest code
(756 names 757, Switzerland); another mistake raises InvalidRequestError naming
the closest valid value.
Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
cl_code: Product classification: "HS" (all HS editions as reported; prefer
it), an edition "H0" to "H5", SITC "SS", "S1" to "S4", BEC
"B4", "B5", for services EBOPS "EB", "EB02", "EB10",
"EB10S"; also "BE" and "TM", which the spec lists and upstream
accepts. "H6" is valid but upstream answered HTTP 500 to all five tries on
2026-10-23 (two reporters, two product codes); "HS" rows carry the edition
the reporter used, e.g. classification_code "H6" for Switzerland 2023.
reporter_code: Reporting areas as UN Comtrade's numeric codes, comma-separated,
e.g. "757" Switzerland, "842" USA, "276" Germany, "156" China,
"757,842", as list_reporters lists them. Some differ from ISO numeric
codes: Switzerland is 757, not 756. Omit for every reporter.
partner_code: Partner areas, comma-separated, as list_partners lists them:
"0" World (the total over all partners), "276" Germany. Omit for every
partner, one row each.
partner2_code: Second partner (consignment) areas, comma-separated, codes of
list_partners; "0" is the total.
period: Years "2023" (annual) or months "202305" (monthly), at most 12
comma-separated, e.g. "2021,2022,2023".
cmd_code: Product codes of cl_code, comma-separated, as
list_commodities(cl_code) lists them: "TOTAL" for all goods,
"AG2", "AG4", "AG6" for every code at that level, codes such as
"0901" or "090111", wildcards such as "27??" (every four-digit code
under 27) or "27*". For services the classification files name "200"
(EB, EB02, EB10) or "S" (EB10S) as the total; recorded counts confirm
"200" on EB10 and EB02, where "TOTAL" counted 0 (EB10). A code
upstream does not have counts 0 too, so a 0 does not prove that a code exists.
flow_code: Trade flows, comma-separated: "X" exports, "M" imports,
"RX" re-exports, "RM" re-imports, also "DX", "FM", "MIP",
"MOP", "XIP", "XOP", "MIF", "XIF"; e.g. "M,X".
mot_code: Modes of transport, comma-separated: "0" the total, "1000" air,
"2100" sea, "3100" railway, "3200" road, "9100" pipelines and
cables. Omit for every mode, one row each.
customs_code: Customs procedures, comma-separated: "C00" the total, "C01"
clearance for home use, "C03" outright exportation. Omit for every
procedure, one row each.
aggregate_by: Upstream parameters to aggregate the results over, comma-separated
from cmdCode, period, partnerCode, partner2Code,
reporterCode, customsCode, motCode; e.g. "cmdCode" sums the
products of "AG2" into one row per remaining breakdown. The aggregated
parameters come back as -2 (cmd_code "-2", partner_code -2)
with classification_code "GG"; the count matches the rows.
breakdown_mode: "plus", upstream's default (omitting it gives the same rows):
every customs procedure, mode of transport and second partner;
"classic": only the total row (partner2_code 0, customs_code
"C00", mot_code 0).
include_desc: Upstream's includeDesc, "Include descriptions of data
variables": fills the *_iso and *_desc fields of get_data rows;
sent on as given.
Inputs: cl_code (required), freq_code (required), type_code (required), period, +10 more.
comtrade_get_dataARead-onlyIdempotent
Fetch UN Comtrade final trade data for one query, up to 100,000 records.
Counts first (one extra call, as get_counts): a count of 0 returns an empty list
without fetching, since no matching data is an answer, not an error; a count above
100,000 raises QueryTooLarge with the count before anything is fetched, because
upstream would cut the answer at 100,000 rows without saying so. Each row carries
every field of upstream's TradeDataRecord under its snake_case name;
primary_value is upstream's primary trade value (taken from the CIF or FOB value,
in cifvalue/fobvalue). Leaving out partner2_code,
customs_code and mot_code returns every breakdown upstream holds (32 rows for
Switzerland's 2023 exports to the World); the row with partner2_code 0,
customs_code "C00" and mot_code 0 is the total, and pinning those three
(or breakdown_mode="classic") returns that row alone. Arguments are checked
before any call; an unknown reporter, partner, customs or transport code raises
UnknownCode, an InvalidRequestError naming the packaged list and the closest
code, another mistake InvalidRequestError naming the closest valid value.
Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
cl_code: Product classification: "HS" (all HS editions as reported; prefer
it), an edition "H0" to "H5", SITC "SS", "S1" to "S4", BEC
"B4", "B5", for services EBOPS "EB", "EB02", "EB10",
"EB10S"; also "BE" and "TM", which the spec lists and upstream
accepts. "H6" is valid but upstream answered HTTP 500 to all five tries on
2026-10-23 (two reporters, two product codes); "HS" rows carry the edition
the reporter used, e.g. classification_code "H6" for Switzerland 2023.
reporter_code: Reporting areas as UN Comtrade's numeric codes, comma-separated,
e.g. "757" Switzerland, "842" USA, "276" Germany, "156" China,
"757,842", as list_reporters lists them. Some differ from ISO numeric
codes: Switzerland is 757, not 756. Omit for every reporter.
partner_code: Partner areas, comma-separated, as list_partners lists them:
"0" World (the total over all partners), "276" Germany. Omit for every
partner, one row each.
partner2_code: Second partner (consignment) areas, comma-separated, codes of
list_partners; "0" is the total.
period: Years "2023" (annual) or months "202305" (monthly), at most 12
comma-separated, e.g. "2021,2022,2023".
cmd_code: Product codes of cl_code, comma-separated, as
list_commodities(cl_code) lists them: "TOTAL" for all goods,
"AG2", "AG4", "AG6" for every code at that level, codes such as
"0901" or "090111", wildcards such as "27??" (every four-digit code
under 27) or "27*". For services the classification files name "200"
(EB, EB02, EB10) or "S" (EB10S) as the total; recorded counts confirm
"200" on EB10 and EB02, where "TOTAL" counted 0 (EB10). A code
upstream does not have counts 0 too, so a 0 does not prove that a code exists.
flow_code: Trade flows, comma-separated: "X" exports, "M" imports,
"RX" re-exports, "RM" re-imports, also "DX", "FM", "MIP",
"MOP", "XIP", "XOP", "MIF", "XIF"; e.g. "M,X".
mot_code: Modes of transport, comma-separated: "0" the total, "1000" air,
"2100" sea, "3100" railway, "3200" road, "9100" pipelines and
cables. Omit for every mode, one row each.
customs_code: Customs procedures, comma-separated: "C00" the total, "C01"
clearance for home use, "C03" outright exportation. Omit for every
procedure, one row each.
aggregate_by: Upstream parameters to aggregate the results over, comma-separated
from cmdCode, period, partnerCode, partner2Code,
reporterCode, customsCode, motCode; e.g. "cmdCode" sums the
products of "AG2" into one row per remaining breakdown. The aggregated
parameters come back as -2 (cmd_code "-2", partner_code -2)
with classification_code "GG"; the count matches the rows.
breakdown_mode: "plus", upstream's default (omitting it gives the same rows):
every customs procedure, mode of transport and second partner;
"classic": only the total row (partner2_code 0, customs_code
"C00", mot_code 0).
include_desc: Upstream's includeDesc, "Include descriptions of data
variables": fills reporter_iso/reporter_desc, the partner and second
partner ones, flow_desc, cmd_desc, customs_desc, mot_desc, the
quantity unit abbreviations, aggr_level and is_leaf; without it they
are None.
Inputs: cl_code (required), freq_code (required), type_code (required), period, +10 more.
comtrade_get_data_availabilityARead-onlyIdempotent
List the UN Comtrade datasets a query covers, per reporter and period, with release dates.
Upstream's getDa: which reporters have published data for which periods, in which
classification, how many records each dataset holds and when it was first and last
released (first_released, last_released, naive datetimes as upstream sends
them). One call. A period nobody reported returns an empty list. Arguments are checked
before the call; an unknown reporter code raises UnknownCode, an
InvalidRequestError naming the packaged list and the closest area, another
mistake InvalidRequestError naming the closest valid value.
Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
cl_code: Classification: "HS" for the data as reported (Switzerland 2023 is
an "H6" dataset), an HS edition "H0" to "H6", SITC "S1" to
"S4", "BE", for services "EB", "EB02", "EB10".
reporter_code: Reporters, comma-separated, as list_reporters lists them:
"757" Switzerland, "842" USA, "276" Germany, "156" China,
"757,842". Omit for every reporter (169 datasets for 2023, annual HS).
period: Years "2023" or months "202305", comma-separated, e.g.
"2021,2022,2023"; unlike get_data, more than 12 are accepted.
published_date_from: Upstream's publishedDateFrom, a day "2024-01-01":
datasets published from then on. A dataset revised in the range counts
(Switzerland 2022, first released 2023-02-01, revised 2024-04-29, is in 2024).
published_date_to: Upstream's publishedDateTo, a day "2024-12-31".
Inputs: cl_code (required), freq_code (required), type_code (required), period, +3 more.
comtrade_get_live_updateARead-onlyIdempotent
List the 50 most recent releases in UN Comtrade's release pipeline, newest first.
Upstream's getLiveUpdate: for each release the reporter (reporter_code, a
string here, e.g. "842"), type_code, freq_code, classification_code,
period, file size, status and release_status (e.g. "Released"),
and four times: started_at and completed_at (UTC), last_updated (a day)
and queued_at (no zone given, kept naive). There is no publication date field;
get_data_availability and get_metadata carry those per dataset. One call, no
arguments. Upstream's count (174 when recorded) is not the number of rows, so it
is not returned.
Inputs: no named parameters.
comtrade_get_metadataARead-onlyIdempotent
List UN Comtrade's publication notes for a reporter's datasets, one per publication.
Upstream's getMetadata: per dataset (reporter and period), a note for its first
publication ("New Data") and one for each revision ("Revised Data"), each with its
publication_date and what the reporter's data rests on: currency, the import
and export conversion factors (Decimal), trade_system ("General" or
"Special"), the valuation ("CIF", "FOB") and partner attribution. One call.
reporter_code and period are not in upstream's spec, but upstream honours them
as the official comtradeapicall package sends them; without reporter_code the
answer holds every reporter's notes, so name one.
Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
cl_code: Classification: "HS" ("H6" is answered the same), SITC
"SS" or "S1" to "S4", "BE", "TM", for services "EB",
"EB02", "EB10".
reporter_code: Reporters, comma-separated, as list_reporters lists them:
"757" Switzerland (38 annual datasets, 1988 onwards), "842" USA,
"276" Germany, "156" China.
period: Years "2023" or months "202305", comma-separated. Omit for every
period.
Inputs: cl_code (required), freq_code (required), type_code (required), period, +1 more.
comtrade_get_mirror_flowsARead-onlyIdempotent
A reporter's reported trade with one partner beside the partner's reported mirror of it.
The two sides of one trade, per product code and period: what the reporter reported
(primary_value, its quantities and weights) and what the partner reported for the
same trade (mirror_primary_value, mirror_qty, ...): for a reporter's exports,
"the import data reported by" the partner. UN Comtrade's Help Center calls the tool
Bilateral Data Comparison, which "puts the reported data and its mirror data
side-by-side, allowing the analysis of bilateral trade asymmetries"
(un-comtrade-tools.md); the two sides differ for documented reasons, imports valued
CIF and exports FOB, partner attribution, time lags, goods passing through third
countries (bilateral-asymmetries.md). One call of upstream's getBilateralData
for goods (typeCode C), which its spec marks "EXPERIMENTAL - USE SPARINGLY"; it
answers at the total of every breakdown (classic mode). data is one
MirrorFlows, not a list: upstream's note, its timestamp_requested (UTC) and
the rows, data.data, one MirrorFlowRecord per product code and period, in
upstream's order (period order in every recording); a code or period upstream holds
nothing for has no row.
The note qualifies the mirror: it counts the partners with a data gap and gives their
share of world trade without naming them, and "the outcome of the mirror data depends
on the availability of other reporters rather than no-trade", so a mirror of 0 is no
evidence of no trade. For Switzerland's 2023 exports Afghanistan's mirror of 0 showed
which partner the gap was, inferred from the counts, not stated; that is no general
rule. primary_value_disc is upstream's, its meaning not stated: in every recorded
row it equals (mirror_primary_value - primary_value) / primary_value (-0.949
for Switzerland's 2023 exports of HS chapter 27 to the USA). mirror2_primary_value
is not described upstream and was 0 in every recorded row; the other mirror2
fields are left out (empty in every recording; get_bilateral_data carries them).
Descriptions are None: getBilateralData filled none even with includeDesc, so
it is not sent; list_reporters and list_partners name the codes. Bounded by
construction at product codes times periods rows, so there is no count call (upstream
offers none here); a bound above 100,000 raises QueryTooLarge before the call.
Over MCP a result above 64 KB (about 60 rows) reaches the agent as a preview of its
text, so name a few product codes or periods per call. Arguments are resolved and
checked before the call; an unknown area raises UnknownCode, an
InvalidRequestError naming the packaged list and the closest area, another mistake
InvalidRequestError naming the closest valid value. meta.request holds the
get_bilateral_data arguments that were sent, codes resolved; meta.total is
upstream's count.
Args:
reporter: The reporting area, as UN Comtrade's code or its ISO alpha-3 code:
"757" or "CHE" Switzerland, "842" or "USA", "276" or "DEU"
Germany, "156" or "CHN" China; list_reporters(search=...) finds them.
Codes are UN Comtrade's, not ISO numeric (Switzerland is 757, not 756).
partner: The partner area whose report is the mirror, as code or ISO alpha-3
code: "842" or "USA" (842, the code the USA reports under, not 840),
"757" or "CHE", "276" or "DEU"; list_partners(search=...)
finds them. "0" World is passed on, upstream's answer to it unrecorded.
commodities: Product codes of cl_code, comma-separated, each naming one code:
"TOTAL" all goods, an HS chapter "27", headings "2709,2710".
Levels such as "AG2" and wildcards such as "27??" are refused (one row
per code and period bounds the call). list_commodities("HS", search="crude")
finds codes.
periods: Years "2022,2023" (annual data) or months "202301" (monthly
data), comma-separated, one format: the format sets freqCode. At most 12,
the bound of the slices, though getBilateralData answered 13
(get_bilateral_data takes more).
flow: The reporter's flow, one of the two getBilateralData takes: "X" exports,
whose mirror is the partner's reported imports, or "M" imports, the spec's
other value (not recorded here).
cl_code: Product classification, "HS" by default and the one recorded: all HS
editions as each reporter reported them (rows name the edition in
classification_code, e.g. "H6"). Checked against the package's list:
an edition "H0" to "H6", SITC "SS" or "S1" to "S4", BEC
"B4", "B5" are accepted but untested here; the Tools spec's "BE4",
"BE5" and "EBSDMX" are refused before the call. EBOPS "EB",
"EB02", "EB10", "EB10S" (services), "BE" and "TM" are
accepted but untested with the pinned typeCode C.
Inputs: flow (required), partner (required), periods (required), reporter (required), +2 more.
comtrade_get_top_partnersARead-onlyIdempotent
A reporter's n largest partners in one product and period, by primary value.
One data/v1/get call for goods (typeCode C) without partnerCode (every
partner), pinned to the total of every breakdown (partner2Code 0, customsCode
C00, motCode 0, breakdownMode classic), with descriptions (includeDesc).
The rows are sorted by primary_value, largest first, here rather than upstream;
partner 0, World, is dropped because it is the total over all partners, not a
partner; the first n rows are returned and nothing else is changed. Areas that
are not countries, such as 490 "Other Asia, nes", stay in the ranking where the
reporter reported them. Bounded by construction at one row per partner (310 in the
packaged partnerAreas.json), so there is no count call. Arguments are resolved and
checked before the call; an unknown reporter raises UnknownCode, an
InvalidRequestError naming the packaged list and the closest area, another
mistake InvalidRequestError naming the closest valid value. meta.request holds
the get_data arguments that were sent, and n.
Args:
reporter: The reporting area, as UN Comtrade's code or its ISO alpha-3 code:
"757" or "CHE" Switzerland, "842" or "USA", "276" or "DEU"
Germany, "156" or "CHN" China; list_reporters(search=...) finds them.
Codes are UN Comtrade's, not ISO numeric (Switzerland is 757, not 756). An
alpha-3 code that several codes share resolves to the one still in use
("DEU" is 276, not 280 Fed. Rep. of Germany until 1990).
commodity: One product code of cl_code: "TOTAL" all goods, an HS chapter
"27", heading "3004" or subheading "300490".
list_commodities("HS", search="medicament") finds codes.
period: One year "2023" (annual data) or month "202305" (monthly data).
flow: One trade flow: "X" exports, "M" imports, "RX" re-exports,
"RM" re-imports.
n: How many partners, at least 1, e.g. 10; fewer come back when fewer
partners have a row.
cl_code: Product classification, "HS" by default: all HS editions as each
reporter reported them (rows name the edition in classification_code, e.g.
"H6"); an edition "H0" to "H5", SITC "SS" or "S1" to "S4",
BEC "B4", "B5" also work. "H6" is valid but upstream answered HTTP 500
to every try on 2026-10-23, so "HS" stays the default. EBOPS "EB",
"EB02", "EB10", "EB10S" (services), "BE" and "TM" are
accepted but untested with the pinned typeCode C.
Inputs: n (required), flow (required), period (required), reporter (required), +2 more.
comtrade_get_trade_balanceARead-onlyIdempotent
Fetch UN Comtrade trade data with a reporter's exports and imports side by side.
Upstream's getTradeBalance, which its spec marks "EXPERIMENTAL - USE SPARINGLY":
one keyed call, no count first. Each row, a TradeBalanceRecord, holds a reporter's
exports (*_x: primary_value_x, qty_x, net_wgt_x, ...) and imports
(*_m) with one partner, second partner, product code, customs procedure, mode of
transport and period, and primary_value_bal, which the spec defines as "X - M":
upstream's value, passed through (54550055814.504944 for Switzerland and the World
in 2023). Without breakdown_mode upstream answers every breakdown (48 rows for
Switzerland and the World, 2023, all goods); breakdown_mode="classic" returns the
total row alone. A query nothing matches returns an empty list. meta.total is
upstream's count. The query must name reporter_code or partner_code, and
cmd_code: upstream offers no count to check a query's size before the call
(countOnly answered 0 for those 48 rows), so a broader query is refused before it
is sent. Arguments are checked before the call; an unknown reporter, partner, customs
or transport code raises UnknownCode, an InvalidRequestError naming the
packaged list and the closest code, another mistake InvalidRequestError naming the
closest valid value. The spec says a free-tier key that is not on UN Comtrade's
allow-list is refused with HTTP 403 "User not allowed" (AuthError); the key the
package was recorded with was answered (2026-10-28).
Args:
type_code: "C" goods or "S" services.
freq_code: "A" annual or "M" monthly.
cl_code: Product classification, checked against the package's list: "HS"
(all HS editions as reported, the one recorded here; rows name the edition in
classification_code, e.g. "H6"), an edition "H0" to "H6",
SITC "SS", "S1" to "S4", BEC "B4", "B5", "BE",
"TM", for services EBOPS "EB", "EB02", "EB10", "EB10S".
The Tools spec lists HS, S1 to S4, BE4, BE5, EB,
EB02, EB10 and EBSDMX; BE4, BE5 and EBSDMX are not in
the package's list (upstream refused BE5 on data/v1/get and
EBSDMX on getDa) and are refused before the call.
reporter_code: Reporting areas as UN Comtrade's numeric codes, comma-separated,
e.g. "757" Switzerland, "842" USA, "276" Germany, "156" China,
"757,842", as list_reporters lists them. Some differ from ISO numeric
codes: Switzerland is 757, not 756. Required unless partner_code is given.
period: Years "2023" (annual) or months "202305" (monthly), at most 12
comma-separated, e.g. "2021,2022,2023".
partner_code: Partner areas, comma-separated, as list_partners lists them:
"0" World (the total over all partners), "276" Germany. Required
unless reporter_code is given; omitted, upstream's default applies, which
on get_data is every partner, one row each.
partner2_code: Second partner (consignment) areas, comma-separated, codes of
list_partners; "0" is the total.
cmd_code: Product codes of cl_code, comma-separated, as
list_commodities(cl_code) lists them: "TOTAL" for all goods,
"AG2" for every chapter, codes such as "27", "0901" or
"090111", wildcards such as "27??".
customs_code: Customs procedures, comma-separated: "C00" the total, "C01"
clearance for home use, "C03" outright exportation. Omit for every
procedure, one row each.
mot_code: Modes of transport, comma-separated: "0" the total, "1000" air,
"2100" sea, "3100" railway, "3200" road, "9100" pipelines and
cables. Omit for every mode, one row each.
aggregate_by: Upstream parameters to aggregate the results over, comma-separated
from cmdCode, period, partnerCode, partner2Code,
reporterCode, customsCode, motCode, e.g. "cmdCode"; sent on as
given (not recorded on this operation; on get_data the aggregated
parameters come back as -2).
breakdown_mode: Omitted, upstream's default: every customs procedure, mode of
transport and second partner, one row each. "classic": the total row only
(customs_code "C00", mot_code 0, partner2_code 0). "plus",
the spec's other value, gives every breakdown on get_data.
include_desc: Upstream's includeDesc, "Include descriptions of data
variables": with it the recorded rows have reporter_iso/reporter_desc,
the partner and second partner ones, cmd_desc, customs_desc,
mot_desc, the quantity unit abbreviations, aggr_level and is_leaf
filled; no answer with rows was recorded without it.
Inputs: cl_code (required), freq_code (required), type_code (required), period, +9 more.
comtrade_get_world_tradeARead-onlyIdempotent
Every reporter's trade in one product with the World for one period, largest first.
One data/v1/get call for goods (typeCode C) without reporterCode (every
reporter) and with partner 0, World, pinned to the total of every breakdown
(partner2Code 0, customsCode C00, motCode 0, breakdownMode classic),
with descriptions (includeDesc): one row per reporter that reported the period
(167 for 2023 imports of HS chapter 27 when recorded), sorted by primary_value,
largest first. Bounded by construction at one row per reporter (255 in the packaged
Reporters.json), so there is no count call. Arguments are checked before the
call; a mistake raises InvalidRequestError naming the closest valid value.
meta.request holds the get_data arguments that were sent.
Args:
commodity: One product code of cl_code: "TOTAL" all goods, an HS chapter
"27", heading "2709" or subheading "270900".
list_commodities("HS", search="crude") finds codes.
period: One year "2023" (annual data) or month "202305" (monthly data).
Recent periods fill as reporters publish; get_data_availability tells who
has.
flow: One trade flow: "X" exports, "M" imports, "RX" re-exports,
"RM" re-imports.
cl_code: Product classification, "HS" by default: all HS editions as each
reporter reported them (rows name the edition in classification_code, e.g.
"H6"); an edition "H0" to "H5", SITC "SS" or "S1" to "S4",
BEC "B4", "B5" also work. "H6" is valid but upstream answered HTTP 500
to every try on 2026-10-23, so "HS" stays the default. EBOPS "EB",
"EB02", "EB10", "EB10S" (services), "BE" and "TM" are
accepted but untested with the pinned typeCode C.
Inputs: flow (required), period (required), commodity (required), cl_code.
comtrade_list_classificationsARead-onlyIdempotent
List UN Comtrade's reference files, the product classifications among them, by category.
Answered from upstream's index of the files, ListofReferences.json, as packaged
with this version (reference/ListofReferences.json), without an upstream call;
meta.retrieved_at is when the package fetched it, meta.vintage is None.
28 rows when packaged, one per file: its category ("flow", "reporter",
"cmd:HS"), the variable it lists ("Product [HS 2022]"), upstream's
description and where the file is served, fileuri. A category
cmd:<clCode> is a product classification, 19 of them: the cl_code that
get_data and list_commodities take ("cmd:H6" is "H6", HS 2022).
Args:
category: Keep the row of this category, as upstream writes it, e.g.
"cmd:HS", "cmd:H6", "cmd:EB10", "flow", "reporter",
"qtyunit". Omit for every row.
Inputs: category.
comtrade_list_codesARead-onlyIdempotent
List the values one UN Comtrade parameter takes, each with upstream's words for it.
Answered from the list packaged with this version (reference/<param>.json),
without an upstream call; meta.endpoint is the reference file or the spec the list
came from, meta.retrieved_at when the package fetched it, meta.vintage is
None. Each row holds the value under the parameter's name in snake_case
(flow_code, qty_unit_code) and upstream's words for it, under upstream's
names: text from the reference files for flowCode (tradeRegimes.json),
customsCode, motCode and mosCode; qty_abbr and qty_description for
qtyUnitCode; variable and description from ListofReferences.json for
clCode; for typeCode and freqCode text is the spec's wording ("C"
commodities, "A" annual). A value the package takes from the spec carries none:
"MIF" and "XIF" (flowCode), "BE" and "TM" (clCode), and
breakdownMode and aggregateBy, whose descriptions word no value. mosCode
lists ModeOfSupply.json's ids, not proven parameter values (data/v1/get
refused "Mode 1" and accepted "0" and "1"). At most 41 rows
(qtyUnitCode).
Args:
param: The parameter, as upstream names it: "flowCode", "customsCode",
"motCode", "clCode", "typeCode", "freqCode",
"breakdownMode", "aggregateBy", "qtyUnitCode" or "mosCode".
Inputs: param (required).
comtrade_list_commoditiesARead-onlyIdempotent
List the product codes of one UN Comtrade classification, the values cmd_code takes.
Fetched live from upstream's public classification file <cl_code>.json (no key, no
quota) and kept for the life of the process: meta.retrieved_at is when the file
was fetched, the first call's time on a later one. The lists are large: "HS" has
8,262 codes (about 2 MB), each HS edition 6,000 to 7,000, SITC "SS" 7,863, BEC
"B5" 178, EBOPS "EB" 423, so search narrows them. Every row has id (the
code), text and parent; the goods files add is_leaf and aggr_level (0
for TOTAL, then 2, 4 and 6 digits for HS). meta.vintage stays None: the
files carry no release identifier.
Args:
cl_code: The classification, with a file upstream: "HS" (all HS editions
combined), an edition "H0" (1992) to "H6" (2022), SITC "SS"
(combined) or "S1" to "S4", BEC "B4" or "B5", EBOPS "EB"
(combined), "EB02", "EB10" or "EB10S". "BE" and "TM",
which get_data takes, have no file.
search: Keep the rows where this text occurs, ignoring case, in the code (id,
and cmd_code in SS) or the description (text, and
description_original in SS), e.g. "coffee", "crude",
"0901". HS texts start with the code ("0901 - Coffee, ..."). Omit for
every row.
Inputs: cl_code (required), search.
comtrade_list_partnersARead-onlyIdempotent
List the partner areas UN Comtrade records trade with, for partner_code and partner2_code.
Answered from upstream's partnerAreas.json as packaged with this version
(reference/partnerAreas.json), without an upstream call; meta.retrieved_at is
when the package fetched it, meta.vintage is None. 310 rows when packaged:
0 World (the total over all partners), countries in the reporters' code space
(757 Switzerland, 842 USA, 276 Germany, 156 China) and areas that only
occur as partners, such as 899 "Areas, nes" or 756 Switzerland under its ISO
code. search finds a code without reading the whole list.
Args:
search: Keep the rows where this text occurs, ignoring case, in the code
(partner_code), the ISO alpha-3 code or the names (text,
partner_desc, partner_note), e.g. "world", "W00", "USA"
(840 United States of America, 841, 842 USA), "nes". Omit for every row.
Inputs: search.
comtrade_list_reportersARead-onlyIdempotent
List the reporters UN Comtrade has trade data from, with the codes reporter_code takes.
Answered from upstream's Reporters.json as packaged with this version
(reference/Reporters.json), without an upstream call; meta.retrieved_at is
when the package fetched it, meta.vintage is None. 255 rows when packaged,
one per reporter code, current and historical (entry_expired_date is set on codes
no longer used, such as 280 Fed. Rep. of Germany until 1990 or 810 USSR).
Codes are UN Comtrade's, not always ISO numeric: 757 Switzerland (not 756),
842 USA, 276 Germany, 156 China; 97 European Union and 975 ASEAN
are groups (is_group). search finds a code without reading the whole list.
Args:
search: Keep the rows where this text occurs, ignoring case, in the code
(reporter_code), the ISO alpha-3 code or the names (text,
reporter_desc, reporter_note), e.g. "switz", "757", "CHE"
(757 Switzerland, and 690 Seychelles by its name), "germany" (276 Germany,
278 and 280 until 1990). Omit for every row.
Inputs: search.
usda_nass_get_acreageARead-onlyIdempotent
Planted or harvested acreage of a crop for a year, state or national, in acres.
Annual final totals (unit_desc ACRES, domain_desc TOTAL,
prodn_practice_desc ALL PRODUCTION PRACTICES, reference_period_desc
YEAR), so breakdowns by size group, irrigation or biotech type and the in-season
forecasts are left out; get_acreage_forecasts serves the latter. Harvested
acreage comes per utilisation (grain, silage); planted acreage as one figure.
Sorted by state, utilisation and source.
Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS", "WHEAT".
year: Crop year, e.g. 2023.
statistic: AreaStatistic.AREA_PLANTED or AreaStatistic.AREA_HARVESTED.
state: Two-letter state code for the state figure; None returns the national
US TOTAL figure.
Inputs: year (required), commodity (required), statistic (required), state.
usda_nass_get_acreage_forecastsARead-onlyIdempotent
The in-season acreage reports for a crop and year, in acres, oldest first.
Every report except the final figure: the March prospective plantings, the June
acreage report and the monthly forecasts, each row naming its
reference_period_desc (YEAR - JUN ACREAGE, YEAR - AUG FORECAST, ...).
Same fixed filters as get_acreage otherwise, so the series is comparable with
the final figure. Sorted by load_time, then utilisation.
Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS", "WHEAT".
year: Crop year, e.g. 2023.
statistic: AreaStatistic.AREA_PLANTED or AreaStatistic.AREA_HARVESTED.
state: Two-letter state code for the state series; None returns the national
series.
Inputs: year (required), commodity (required), statistic (required), state.
usda_nass_get_census_farmsARead-onlyIdempotent
Census of Agriculture farm counts or land in farms for a year, national, by state or county.
The farm totals of the five-yearly Census (source_desc CENSUS, group_desc
FARMS & LAND & ASSETS, commodity_desc FARM OPERATIONS, class_desc
ALL CLASSES, prodn_practice_desc ALL PRODUCTION PRACTICES,
domain_desc TOTAL), so the breakdowns by farm size, sales class, typology,
organization and the like are left out; get_data reaches them. unit_desc
tells the rows of one place apart: for OPERATIONS the number of farms
("OPERATIONS") and, above the county level, "PCT OF FARM OPERATIONS"; for
AREA OPERATED the land in farms ("ACRES"), "ACRES / OPERATION",
"ACRES / OPERATION, MEDIAN", "PCT OF TOTAL LAND" and, above the county
level, "PCT OF AG LAND", as the 2022 Census publishes them; another year may
carry fewer. value is the figure as published and value_number its parsed
form; cv_percent is the coefficient of variation, None where upstream prints
a code such as "(L)" or "(H)" in its place. Sorted by state, county and
unit. Every county of the country is a large answer (2022: 3,078 rows for
OPERATIONS, 12,312 for AREA OPERATED, counted 2026-10-28), well under the
50,000-record limit: the MCP tool returns its first rows within the result cap
(64 KB, about 100 rows, a projected row being about 600 bytes) with a note, so give
state there. A state's counties are cut too past about 100 rows, so for
AREA OPERATED, four rows a county, a state of more than about 25 counties is cut.
Args:
year: A Census year, e.g. 2022 or 2017; the Census of Agriculture is
taken every five years, and a year without rows under these filters raises
NotFoundError.
statistic: FarmStatistic.OPERATIONS (the number of farms) or
FarmStatistic.AREA_OPERATED (land in farms).
state: Two-letter state code, e.g. StateAlpha.IA: that state's figures, or
with by_county its counties'. None returns the national
US TOTAL figures, or with by_county every county of the country.
The 2022 Census counts no state rows for StateAlpha.PR, and a code
without rows raises NotFoundError.
by_county: True returns county figures (agg_level_desc COUNTY), of
state when given; False, the default, the state or national ones.
Inputs: year (required), statistic (required), state, by_county.
usda_nass_get_county_productionARead-onlyIdempotent
County production of a crop for a year, one row per county, utilisation and practice.
Annual final estimates (statisticcat_desc PRODUCTION, reference_period_desc
YEAR) at agg_level_desc COUNTY, sorted by state, county, utilisation and
practice. unit_desc names the unit, "BU" for grain and "TONS" for silage;
value is the quantity.
Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS", "WHEAT".
year: Crop year, e.g. 2023.
state: Two-letter state code to restrict to one state; None returns every
county in the country.
Inputs: year (required), commodity (required), state.
usda_nass_get_county_yieldARead-onlyIdempotent
County yields of a crop for a year, one row per county, utilisation and practice.
Annual final estimates (statisticcat_desc YIELD, reference_period_desc
YEAR) at agg_level_desc COUNTY, sorted by state, county, utilisation and
practice. unit_desc names the unit, "BU / ACRE" for grain and "TONS / ACRE"
for silage; value is the yield.
Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS", "WHEAT".
year: Crop year, e.g. 2023. County estimates for a year appear the following
spring.
state: Two-letter state code to restrict to one state; None returns every
county in the country, which stays under the 50,000-record limit for one crop
and year.
Inputs: year (required), commodity (required), state.
usda_nass_get_crop_conditionARead-onlyIdempotent
Weekly crop condition: the percentage of a crop rated very poor through excellent.
One row per week and category, from the NASS Crop Progress survey
(statisticcat_desc CONDITION, freq_desc WEEKLY), sorted by week.
unit_desc names the category and value is the percentage.
Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS",
"WINTER WHEAT".
year: Crop year, e.g. 2024.
state: Two-letter state code for the state series; None returns the
national US TOTAL series.
category: One of ConditionCategory.PCT_VERY_POOR, PCT_POOR, PCT_FAIR,
PCT_GOOD, PCT_EXCELLENT; None returns all five.
Inputs: year (required), commodity (required), state, category.
usda_nass_get_crop_progressARead-onlyIdempotent
Weekly crop progress: the percentage planted, emerged, silking, harvested and so on.
One row per week and stage, from the NASS Crop Progress survey (statisticcat_desc
PROGRESS, freq_desc WEEKLY), sorted by week. Stages differ by crop;
unit_desc names each one and value is the percentage.
Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS",
"WINTER WHEAT", "COTTON"; list_param_values("commodity_desc")
lists them.
year: Crop year, e.g. 2024.
state: Two-letter state code for the state series; None returns the
national US TOTAL series.
stage: A single stage, e.g. ProgressStage.PCT_PLANTED,
ProgressStage.PCT_SILKING, ProgressStage.PCT_HARVESTED; the enum
lists every stage any crop uses, and None returns every stage of this
crop.
Inputs: year (required), commodity (required), stage, state.
usda_nass_get_dataARead-onlyIdempotent
Fetch published Quick Stats estimates for a set of filters, up to 50,000 records a call.
Without split_by_year, calls get_counts first: a count of zero returns an empty
result without a second call, and a count above 50,000 raises QueryTooLarge with
the count and a hint (narrower filters, or split_by_year) before anything is
fetched. With split_by_year, a two-sided year range is fetched year by year, each
year counted first and no count of the range sent; year__GE alone is counted
first and split by year only when that count is above 50,000; year is counted
first, and above 50,000 still raises QueryTooLarge. meta.total is the count
get_counts reported, 0 for the empty result, and the yearly counts summed for
a split. Each record carries every Quick Stats column;
value is the published figure as a string ("510,000", or a suppression code
such as "(D)") and value_number the parsed number.
Args:
filters: Quick Stats columns, optionally suffixed with an operator, mapped to
values; the same shape and the same checks as for get_counts: an
unknown value of a packaged parameter raises UnknownCode naming the
list, its fetch date and the closest known values, or pointing at
list_param_values (the tool usda_nass_list_param_values) when none
is close. A query that stays well under the limit names the commodity, the
statistic, the level and the time, e.g.
{"commodity_desc": "CORN", "statisticcat_desc": "AREA PLANTED", "agg_level_desc": "STATE", "state_alpha": "VA", "year": 2012}. Quick Stats
keeps one bound on year per query (recorded 2026-10-28): it counts
year__GE with year__LE as year__GE alone, in either order, and
drops year__GE beside year__LT, so a two-sided year range is served
only by split_by_year.
split_by_year: True fetches the years one at a time where one call cannot serve
them, splitting one call into at most 20 years in Python and over HTTP and 5 by
default on the MCP server, whose --split-years sets 1 to 20. The filters
bound the years in one of three forms, checked before any call: year
(2022), year__GE with year__LE (2020 and 2023), or
year__GE alone, up to the current UTC year. Another year filter
(year__LE alone, year__GT, year__NE, ...), a mix or none raises
InvalidRequestError naming the three forms, and a year__GE or
year__LE past the current UTC year raises it naming that year. year is
counted and fetched once, as without the flag; over the limit it raises
QueryTooLarge naming the year. year__GE with year__LE is always
split, without a count of the range, which Quick Stats would count as
year__GE alone; more years than the ceiling raise InvalidRequestError
naming it before any call. year__GE alone is counted first and fetched once
when the count is within the limit, however far back it starts; over the limit
it is split, and more years than the ceiling raise InvalidRequestError
naming it after that count, before the split. A split counts each year with
year=<y> in place of the year filters, every year before the first fetch, so
a year over 50,000 on its own raises QueryTooLarge naming it before anything
is fetched; it then fetches each year holding records, the records in year
order, each year's in upstream's order. A year counting 0 is skipped: it has no
records, or none published yet, which Quick Stats does not tell apart;
meta.vintage stays None, since Quick Stats names no release. Cost: up to
two keyed calls per year, plus the first count for year__GE alone, paced at
30 a minute, so 5 years take up to 11 calls and 20 years up to 41, about 80
seconds. meta.request carries split_by_year beside the filters.
False, the default, never splits.
Inputs: filters (required), split_by_year.
usda_nass_get_grain_stocksARead-onlyIdempotent
Quarterly grain stocks of a commodity in a year, on farm, off farm and in total, in bushels.
The NASS Grain Stocks estimates (statisticcat_desc STOCKS, unit_desc
BU, domain_desc TOTAL, freq_desc POINT IN TIME, source_desc
SURVEY), state or national, every stocks day of the year together: one row per
day, position and class, sorted by day (begin_code, then
reference_period_desc), then util_practice_desc, then class_desc.
reference_period_desc names the day, FIRST OF MAR, FIRST OF JUN,
FIRST OF SEP or FIRST OF DEC, and begin_code its month (03 ... 12).
util_practice_desc tells the position as upstream spells it for the commodity:
for corn GRAIN (the total), ON FARM, GRAIN and OFF FARM, GRAIN; for
soybeans and wheat ALL UTILIZATION PRACTICES (the total), ON FARM and
OFF FARM. class_desc is ALL CLASSES; wheat's durum comes as rows of its
own, class_desc SPRING, DURUM, where NASS publishes it, as in the national
estimates. value is the quantity in bushels as published and value_number its
parsed form.
Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS",
"WHEAT"; list_param_values("commodity_desc") lists them.
year: Year of the stocks days, e.g. 2024 for the stocks on 1 March, 1 June,
1 September and 1 December 2024; the current year returns only the stocks
days published so far.
state: Two-letter state code for the state estimates, e.g. "IA", "ND";
None returns the national US TOTAL estimates.
Inputs: year (required), commodity (required), state.
usda_nass_get_livestock_inventoryARead-onlyIdempotent
Head counts of cattle, hogs or sheep on hand on the survey days of a year, by class.
Survey inventories (statisticcat_desc INVENTORY, unit_desc HEAD,
domain_desc TOTAL, freq_desc POINT IN TIME, source_desc
SURVEY), state or national, one row per survey day, class and short_desc
(cattle on feed carry the class ALL CLASSES with prodn_practice_desc
ON FEED), sorted by the day (begin_code, its month), then
reference_period_desc, class_desc and short_desc.
reference_period_desc names the day: FIRST OF JAN in the national cattle
series of 2024; the four quarterly days FIRST OF MAR, FIRST OF JUN,
FIRST OF SEP and FIRST OF DEC in Iowa's hogs series of 2024. The whole herd is
the class INCL CALVES for cattle, ALL CLASSES for hogs and INCL LAMBS for
sheep. value is the head count as published.
Args:
commodity: Upstream commodity_desc: LivestockCommodity.CATTLE,
LivestockCommodity.HOGS or LivestockCommodity.SHEEP.
year: Year of the survey days, e.g. 2024.
state: Two-letter state code for the state series, e.g. StateAlpha.IA,
StateAlpha.TX; None returns the national US TOTAL series.
class_desc: One upstream class_desc to keep, e.g. "INCL CALVES",
"COWS, BEEF" or "COWS, MILK" for cattle, "ALL CLASSES",
"BREEDING" or "MARKET" for hogs, "INCL LAMBS" for sheep; None
returns every class. A class with no record for the commodity, year and
place raises NotFoundError.
Inputs: year (required), commodity (required), state, class_desc.
usda_nass_get_milk_productionARead-onlyIdempotent
Milk produced in a year, in pounds, by month and quarter and for the year.
The milk production series, state or national (commodity_desc MILK,
class_desc ALL CLASSES, statisticcat_desc PRODUCTION, unit_desc
LB, domain_desc TOTAL, source_desc SURVEY; short_desc
MILK - PRODUCTION, MEASURED IN LB); ALL CLASSES leaves out the manufactured
dairy products (dry and condensed milk) that upstream files nationally under the same
statistic and unit. Sorted by frequency, then period: the year first
(freq_desc ANNUAL, reference_period_desc YEAR), then the months, each
quarter (JAN THRU MAR, ...) after its first month, since upstream files months and
quarters alike as MONTHLY. value is the quantity in pounds as published.
Args:
year: Calendar year, e.g. 2024.
state: Two-letter state code for the state series, e.g. StateAlpha.WI,
StateAlpha.CA; None returns the national US TOTAL series.
frequency: FreqDesc.MONTHLY (the months and quarters) or FreqDesc.ANNUAL
(the year) to keep one; None returns both. FreqDesc.WEEKLY,
FreqDesc.SEASON and FreqDesc.POINT_IN_TIME raise NotFoundError,
since upstream files no milk production under them.
Inputs: year (required), state, frequency.
usda_nass_get_prices_receivedARead-onlyIdempotent
Prices farmers received for a commodity in a year, monthly and marketing-year.
statisticcat_desc PRICE RECEIVED at domain_desc TOTAL, state or
national, sorted by frequency and period: the marketing-year average first, then
the months. The national series also carries the price as a percentage of parity
(unit_desc "PCT OF PARITY") next to the dollar price; the column tells them
apart.
Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS", "MILK",
"CATTLE".
year: Calendar year of the months, e.g. 2023.
state: Two-letter state code for the state series; None returns the
national series.
frequency: FreqDesc.MONTHLY or FreqDesc.ANNUAL to keep one; None
returns both.
Inputs: year (required), commodity (required), state, frequency.
usda_nass_get_productionARead-onlyIdempotent
The final production or yield of a crop for a year, state or national.
Annual final figures (reference_period_desc YEAR, domain_desc TOTAL,
prodn_practice_desc ALL PRODUCTION PRACTICES, freq_desc ANNUAL), so
breakdowns by irrigation and the like and the in-season forecasts are left out;
get_production_forecasts serves the latter. Utilisations, classes and units come
as rows, the columns tell them apart: util_practice_desc grain from silage,
class_desc a crop's classes (wheat's ALL CLASSES, WINTER, ...),
unit_desc the unit (BU, TONS, BU / ACRE), and the value of production
comes as rows with unit_desc $. value is the figure as published,
value_number its parsed form. Sorted by state, utilisation, class, unit and
source. Cost: one keyed call, without a count first; meta.total stays None.
Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS",
"WHEAT", "COTTON"; list_param_values("commodity_desc") lists them.
year: Crop year, e.g. 2023.
statistic: ProductionStatistic.PRODUCTION or ProductionStatistic.YIELD.
state: Two-letter state code for the state figure, e.g. StateAlpha.IA;
None returns the national US TOTAL figure.
Inputs: year (required), commodity (required), statistic (required), state.
usda_nass_get_production_forecastsARead-onlyIdempotent
The in-season production or yield forecasts for a crop and year, oldest first.
The Crop Production reports' forecasts, each row naming its
reference_period_desc (YEAR - AUG FORECAST, YEAR - SEP FORECAST, ...),
selected with reference_period_desc__LIKE FORECAST; the final figure,
YEAR, is get_production's. Annual totals (domain_desc TOTAL,
prodn_practice_desc ALL PRODUCTION PRACTICES, freq_desc ANNUAL), so
breakdowns by irrigation and the like are left out and the series is comparable with
the final figure. Utilisations, classes and units come as rows, the columns tell them
apart: util_practice_desc grain from silage, class_desc a crop's classes
(wheat's ALL CLASSES, WINTER, SPRING, (EXCL DURUM), SPRING, DURUM),
unit_desc the unit (BU, BU / ACRE). value is the figure as published,
value_number its parsed form. Sorted by load_time, then utilisation, class
and unit. Cost: one keyed call, without a count first; meta.total stays None.
Args:
commodity: Upstream commodity_desc, e.g. "CORN", "SOYBEANS",
"WHEAT", "COTTON"; list_param_values("commodity_desc") lists them.
year: Crop year, e.g. 2023.
statistic: ProductionStatistic.PRODUCTION or ProductionStatistic.YIELD.
state: Two-letter state code for the state series, e.g. StateAlpha.IA;
None returns the national series.
Inputs: year (required), commodity (required), statistic (required), state.
usda_nass_list_param_valuesARead-onlyIdempotent
List every value a Quick Stats filter parameter can take, to form valid queries.
Nine lists are answered from data packaged with this version, with no upstream call
(meta.endpoint is "get_param_values", the operation they were fetched from,
and meta.retrieved_at the time they were fetched): source_desc,
sector_desc, group_desc, agg_level_desc, freq_desc, state_alpha,
statisticcat_desc, unit_desc, domain_desc. Every other parameter is
fetched live and cached for 24 hours in this process, so a repeated lookup sends
nothing; meta.retrieved_at is the time the cached answer was fetched.
Args:
param: A Quick Stats column name, e.g. "statisticcat_desc" or "unit_desc"
(packaged), or "commodity_desc", "short_desc", "county_name",
"year" (fetched live). Definitions are in
docs/upstream/param_define.md.
Inputs: param (required).
usda_psd_get_balance_sheetARead-onlyIdempotent
One country's PSD supply and distribution of a commodity in a market year, as one record.
One request to PSDData_GetCountryCommodityDataByYear; its records, one per
attribute, become the entries of attributes, keyed by the attribute's upstream
name ("Production", "Imports", "Ending Stocks", 15 of them for wheat in
the United States), in upstream order. Each entry carries attribute_id,
unit_id, value, calendar_year and month exactly as the record had
them. Units differ per attribute (wheat US: 1000 HA for area, 1000 MT for
quantities, MT/HA for yield), so read each entry's unit_id (enums.UnitId).
Nothing is derived, converted or renamed. Names are not unique upstream: an id
whose name the packaged list gives to several ids ("Total Disappearance" is 126
and 173, "Fresh Dom. Consumption" 133 and 135) is always keyed with its id,
"Total Disappearance (126)", so an id has the same key in every answer of a
package version; an id the packaged list lacks is keyed "attribute <id>". Keys
come from the packaged list: a reference refresh that renames an attribute, or adds
an id under an existing name, changes keys and is a breaking change (conventions
§12), recorded in the CHANGELOG. meta.vintage is the PSD release that last
revised the figures ("2026-07"); meta.published_at stays empty, since PSD
gives no day. Codes and the year are checked before the call. Valid codes without
data (PSD answers an empty list) raise NotFoundError, a market year without data
errors.NoDataForYear, both naming commodity, country and year.
Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
country_code: PSD country code (not ISO), e.g. "US" (United States), "BR"
(Brazil), "E4" (European Union). For the world use get_world_data.
market_year: PSD market year, e.g. 2023, 2022, 2021; data goes back to
1960 for most commodities.
Inputs: market_year (required), country_code (required), commodity_code (required).
usda_psd_get_dataARead-onlyIdempotent
PSD supply and distribution forecasts for one commodity and market year, by country.
One record per country and attribute (area, production, imports, exports,
consumption, stocks, ...): attribute_id and unit_id are PSD's integer ids,
which enums.AttributeId and enums.UnitId name; value is in that unit.
Codes and the year are checked against the packaged lists before any call; an
unknown code raises InvalidRequestError naming the closest ones. Each record's
calendar_year and month are the PSD release that last revised it: for one
country all records share one release, for every country they differ by country.
meta.vintage is the latest of them as upstream names it ("2026-07");
meta.published_at stays empty, since PSD gives no day. An empty list means PSD
has no records for that combination; a market year without data raises
NotFoundError. Every country is up to about 1,900 rows (1,875 for corn in 2023).
Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
market_year: PSD market year, e.g. 2023; data goes back to 1960 for most
commodities.
country_code: PSD country code (not ISO), e.g. "US" (United States), "BR"
(Brazil), "E4" (European Union). Omit it (None) for every country:
one record per country and attribute. For the world total use
get_world_data.
Inputs: market_year (required), commodity_code (required), country_code.
usda_psd_get_latest_releaseARead-onlyIdempotent
Which countries and market years PSD's newest release of a commodity revised.
One request to PSDData_GetDataReleaseInfo, which lists the last release of every
country and market year (7,754 records for wheat); the records of the newest
release_year and release_month are kept, unchanged and in upstream's order.
For wheat as recorded on 2026-10-23 that was release 2026-10, 146 records: 123
countries for market year 2026 and a few revisions of earlier years.
meta.vintage names the release ("2026-10") in the form meta.vintage of
get_data takes, so a stored vintage older than it means the listed countries and
market years have changed since. To poll, pass your stored vintage as since: the
answer is the newest release's records when that release is later than since,
and an empty list when it is not, with meta.vintage still naming the newest
release, so an empty list says nothing newer exists. A commodity without any release
gives an empty list and meta.vintage None; meta.published_at stays empty,
since PSD gives no day. A release that adds a market year and revises earlier ones
lists many records: the wheat list recorded on 2026-10-23 had 146 records of 2026-10
and 130 more still carrying 2026-09, so the September answer held between 130 and 276
rows. get_release_dates(commodity_code, market_year=..., country_code=..., since=...) returns any part of the list.
Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
since: A release month "YYYY-MM", e.g. "2026-09", typically the
meta.vintage you stored last time: the newest release's records come back
only when that release is later (strictly after), else an empty list.
None always returns the newest release's records.
Inputs: commodity_code (required), since.
usda_psd_get_release_datesARead-onlyIdempotent
When PSD last revised each country and market year of a commodity: poll for releases.
One record per country and market year: release_year and release_month name
the PSD release, a month without a day. Compare them with a stored meta.vintage
of get_data, or pass that vintage as since, to fetch only what changed.
Upstream answers every country and every market year since 1960 at once (7,754
records for wheat), ordered by market year; market_year, country_code and
since keep only the matching records, after the one call, in upstream's order.
Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
market_year: Keep only this PSD market year, e.g. 2023; None keeps all.
country_code: Keep only this PSD country code (not ISO), e.g. "US", "BR";
None keeps all.
since: Keep only the records revised in a release later than this month,
"YYYY-MM", e.g. "2026-09"; the form meta.vintage takes, so a
stored vintage passes as it is, and that release itself is not kept (strictly
after). None keeps all.
Inputs: commodity_code (required), since, market_year, country_code.
usda_psd_get_time_seriesARead-onlyIdempotent
One country's PSD figures for a commodity over a range of market years.
One request to PSDData_GetCountryCommodityDataByYear per market year, oldest
first, at the client's pace of one request per second, and each counts against
api.data.gov's quota of 1,000 requests per hour per key: 2021 to 2023 is three
requests and about three seconds, 1960 to 2026 sixty-seven, so ask for the years you
need; a range of more than 100 market years is refused. Of each answer the records
of the attributes asked for, or all of them when attribute_id is omitted, are
kept exactly as upstream sent them, ordered by market year and within a year in
upstream's order: value is in its unit_id, and calendar_year and
month name the release that last revised that year, which may differ from year
to year. A market year PSD has no data for (its empty HTTP 404, recorded for 1900),
or whose answer has no record for the attributes, is absent from the list: no gap is
filled, nothing interpolated, no error raised; a range without any record is an
empty list. A year beyond PSD's forecasts is expected to answer the same 404 (not
recorded) and still costs its request. Any other error, the gateway's own 404
included, is raised. meta.vintage is the latest release across the records
("2026-07"); meta.published_at stays empty. Codes, every attribute id, both
years and the range are checked before the first request.
Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
country_code: PSD country code (not ISO), e.g. "US" (United States), "BR"
(Brazil), "E4" (European Union).
start_year: First PSD market year, 1960 or later (PSD: "PSD Database has data
for most commodities since year 1960"), e.g. 2021.
end_year: Last PSD market year, included, e.g. 2023; not before
start_year and at most 99 years after it. No other bound.
attribute_id: PSD attribute id, or a list of them, e.g. 28 (Production),
[28, 88] (Production and Exports), 176 (Ending Stocks);
list_commodity_attributes lists them. Omit it (None) for every
attribute of each answer, 15 a year for wheat in the United States. An empty
list is refused.
Inputs: end_year (required), start_year (required), country_code (required), commodity_code (required), +1 more.
usda_psd_get_top_countriesARead-onlyIdempotent
The n countries with the largest value of one PSD attribute for a commodity and year.
One request to PSDData_GetCommodityDataByYear (every country); its records with
attribute_id are sorted by value, largest first, and the first n kept,
each exactly as upstream sent it. Equal values keep upstream's order. Values are
compared as sent, with no unit check: each record carries its own unit_id, the
unit of its value (in the recorded answers, wheat and corn 2023, every country
reports an attribute in the same unit). By default nothing is excluded: PSD's country
list holds groupings that rank alongside countries, above all the European Union
("E4", second in wheat production for 2023), and residual aggregates such as
"T3" (Africa, NEC), "X8" (Southern Asia NEC) and "Z7" (Other Pacific
Islands, NEC); exclude_groupings=True leaves those out, and region_code keeps
the countries of one PSD region. The data records carry no region, so each record's
country is looked up in the packaged country list; a country it lacks has no region
and is left out when region_code is given. meta.vintage is the latest release
among every record that was ranked, after region_code and exclude_groupings
apply, not only the n returned, since each of them could have changed the order;
for wheat 2023 that is "2026-10", and None when nothing was ranked.
meta.published_at stays empty. Codes and arguments are checked before the call;
a market year without data raises NotFoundError.
Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
market_year: PSD market year, e.g. 2023, 2022, 2021.
attribute_id: PSD attribute id to rank by, e.g. 28 (Production), 88
(Exports), 57 (Imports), 176 (Ending Stocks);
list_commodity_attributes lists them.
n: How many records to keep, at least 1, e.g. 5, 10 (the default); more
than the countries reporting the attribute returns them all.
region_code: Rank only the countries of this PSD region, as list_countries
gives it, e.g. "R04" (South America), "R18" (East Asia), "R15"
(Africa, NEC and three more, a region list_regions lacks). A code no
packaged country carries is refused; "R00" (World) is one, and the world
total is get_world_data's. Omit (None) for every region.
exclude_groupings: True leaves PSD's aggregates out of the ranking: "E4"
European Union, "E2" EU-15, "E3" EU-25, "C1" Caribbean Basin,
"T3" Africa, NEC, "X8" Southern Asia NEC, "Z7" Other Pacific
Islands, NEC and "ZZ" Other. False, the default, ranks them like
countries.
Inputs: market_year (required), attribute_id (required), commodity_code (required), n, +2 more.
usda_psd_get_world_dataARead-onlyIdempotent
PSD supply and distribution forecasts for one commodity and market year, world total.
One record per attribute, aggregated by PSD over every applicable country
(country_code "00"). attribute_id and unit_id are PSD's integer ids,
which enums.AttributeId and enums.UnitId name; value is in that unit.
meta.vintage is the PSD release that last revised the figures, as upstream names
it ("2026-10"), the latest release of any country for this commodity and market
year (in the whole answers recorded on 2026-10-23, commit 07b88ad);
meta.published_at stays empty, since PSD gives no day. The code and the
year are checked before any call; a market year without data raises
NotFoundError.
Args:
commodity_code: PSD commodity code, seven digits, e.g. "0410000" (Wheat),
"0440000" (Corn), "2222000" (Oilseed, Soybean).
market_year: PSD market year, e.g. 2023; data goes back to 1960 for most
commodities.
Inputs: market_year (required), commodity_code (required).
usda_psd_list_commoditiesARead-onlyIdempotent
List PSD's commodities with their codes, the values commodity_code takes.
Answered from PSDData_GetCommodities as packaged with this version
(reference/commodities.json), without an upstream call: 63 commodities when
packaged, in upstream order, e.g. "0410000" Wheat, "0440000" Corn,
"2222000" Oilseed, Soybean. meta.retrieved_at is when the package fetched the
list (2026-10-28, UTC); meta.vintage is empty, as upstream gives the list no
release identifier.
Args:
search: Keep the commodities where this text occurs, ignoring case, in the code
or the name, e.g. "wheat" (0410000 Wheat), "soybean" (meal, oil and
oilseed, each also "(Local)"), "0440000" (Corn). Omit (None) for all.
Inputs: search.
usda_psd_list_commodity_attributesARead-onlyIdempotent
List PSD's commodity attributes with their ids, the attribute_id of every data record.
Answered from PSDData_GetCommodityAttributes as packaged with this version
(reference/commodityAttributes.json), without an upstream call: 85 attributes
when packaged, in upstream order, e.g. 28 Production, 57 Imports, 88
Exports, 176 Ending Stocks. Names are not unique: "Total Disappearance" is
126 and 173, "Fresh Dom. Consumption" 133 and 135; the id tells them apart.
enums.AttributeId names the same ids. meta.retrieved_at is when the package
fetched the list (2026-10-28, UTC); meta.vintage is empty, as upstream gives the
list no release identifier.
Args:
search: Keep the attributes where this text occurs, ignoring case, in the id
(as digits) or the name, e.g. "stocks", "disappearance" (126 and 173
Total Disappearance, 151 Other Disappearance), "28" (28 Production, and
128 Dom. Leaf Consumption: the id matches as text). Omit (None) for all.
Inputs: search.
usda_psd_list_countriesARead-onlyIdempotent
List PSD's countries with their codes and regions, the values country_code takes.
Answered from PSDData_GetCountries as packaged with this version
(reference/countries.json), without an upstream call: 251 countries when
packaged, in upstream order, each with its PSD region (list_regions) and its GENC
code where upstream has one. Codes are PSD's own, not ISO: "US" United States,
"BR" Brazil, "CH" China, "E4" European Union; aggregates such as "T3"
Africa, NEC have no GENC code. meta.retrieved_at is when the package fetched the
list (2026-10-28, UTC); meta.vintage is empty, as upstream gives the list no
release identifier.
Args:
region_code: Keep the countries of this PSD region, spelled exactly as
list_regions spells it, e.g. "R01" (North America, 5 countries),
"R05" (European Union), "R11" (Sub-Saharan Africa). "R15" holds
four countries (Africa, NEC; Fernando Po; French Equatorial Africa; Other)
although list_regions lacks it. A code no country carries yields an
empty list. Omit (None) for every region.
search: Keep the countries where this text occurs, ignoring case, in the code,
the name or the GENC code, e.g. "united" (TC United Arab Emirates, UK
United Kingdom, US United States), "USA" (US United States, by its GENC
code), "E4", "brazil". Omit (None) for every country.
Inputs: search, region_code.
usda_psd_list_regionsARead-onlyIdempotent
List PSD's regions with their codes, the values region_code of list_countries takes.
Answered from PSDData_GetRegions as packaged with this version
(reference/regions.json), without an upstream call: 15 regions when packaged, in
upstream order, from "R00" World and "R01" North America to "R18" East
Asia. Upstream's list lacks "R15", the region of four countries in
list_countries (Africa, NEC and three more); it is kept as upstream sends it.
meta.retrieved_at is when the package fetched the list (2026-10-28, UTC);
meta.vintage is empty, as upstream gives the list no release identifier.
Inputs: no named parameters.
usda_psd_list_units_of_measureARead-onlyIdempotent
List PSD's units of measure with their ids, the unit_id of every data record.
Answered from PSDData_GetUnitsOfMeasure as packaged with this version
(reference/unitsOfMeasure.json), without an upstream call: 42 units when
packaged, in upstream order, e.g. 8 (1000 MT), 4 (1000 HA), 26 (MT/HA).
Descriptions are upstream's, padded with spaces to 20 characters
("(1000 MT) "). enums.UnitId names the same ids.
meta.retrieved_at is when the package fetched the list (2026-10-28, UTC);
meta.vintage is empty, as upstream gives the list no release identifier.
Inputs: no named parameters.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 46 tools
Most tools within each namespace (NASS, PSD, Comtrade) target distinct resources, but several pairs overlap heavily: comtrade_get_bilateral_data and comtrade_get_mirror_flows wrap the same experimental getBilateralData operation with two output shapes, and usda_psd_get_latest_release vs usda_psd_get_release_dates, usda_psd_get_data vs get_balance_sheet vs get_world_data, and comtrade_get_comtrade_releases vs get_live_update all require careful reading to distinguish. The extremely detailed descriptions help, but the boundaries are still fuzzy in places.
All 46 tools follow a consistent snake_case verb_noun pattern with a clear namespace prefix (usda_nass_*, usda_psd_*, comtrade_*), and the list_* / get_* families are applied uniformly. No camelCase or mixed verb style appears anywhere.
46 tools is well above the 25+ threshold for 'too many' and feels heavy for a retrieval server, especially given the near-duplicate wrapper tools and numerous list_* helpers that could be folded together. Splitting across three data providers justifies some breadth, but not this many tools.
The surface covers retrieval, reference listing, counting, availability and release tracking across all three data sources, with few dead ends. Minor gaps exist (e.g. no consolidated multi-param reference lookup, no caching/export helpers), but agents can work around them.
Maintenance
Related MCP Connectors
MCP server for mandates, delegation, policy-gated execution, credential grants, and audit.
Supabase Edge Functions MCP server with allowlisted tools and PostgreSQL RLS.
Streamable HTTP MCP gateway for NV oOS fleets — one API key, namespaced tools, quotas and policy.
Exposes FEDLIN's public security scanners as agent-callable tools over Streamable HTTP.
Related MCP Servers
- FlicenseNot gradedqualityCmaintenanceThis server exposes local stdio MCP tools as HTTP/SSE endpoints, enabling remote clients like Claude Desktop to call them. It supports single-tool and aggregated modes with authentication, auto-restart, and hot reload.-
- AlicenseNot gradedqualityDmaintenanceEnables serving multiple MCP toolkits behind one server with capability-based access control, so different callers see and can call only the tools they are authorized for, over stdio or streamable HTTP with bearer-token auth.MIT
- AlicenseNot gradedqualityBmaintenanceEnables connecting multiple remote HTTP MCP servers through a single local stdio endpoint, handling OAuth authentication, token refresh, and namespace-scoped tools.MIT
- AlicenseNot gradedqualityBmaintenanceAggregates multiple MCP backend servers behind a single HTTP/SSE endpoint, exposing all tools and resources with name-prefixed routing, hot reload, and structured request logging.MIT