comtrade
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
xippios-comtrade
Typed Python client, MCP server and FastAPI routes for UN Comtrade, part of the xippios SDK family. Names and semantics follow the upstream documentation; every response carries its metadata (source, endpoint, retrieved_at, request).
Scope
Of UN Comtrade's API the package wraps fifteen of the 29 operations that its five API
products document (docs/upstream/apidocs/). Of Comtrade it wraps the final data, data/v1/get,
which count_data asks with countOnly and get_data asks for the rows, the availability of
the datasets, data/v1/getDa, their publication notes, data/v1/getMetadata, the release
pipeline, data/v1/getLiveUpdate, and the tariff lines as each reporter files them with the
availability of their datasets, data/v1/getTariffline and data/v1/getDaTariffline. The
spec answers the first with HTTP 403 "User not allowed" for a free key not on its allow-list,
which the task raises as AuthError; the free key that the package was recorded with reached
both. Of Public, which needs no key, it wraps the recent releases,
public/v1/getComtradeReleases, the shares of world trade, public/v1/getWorldShare, the two
previews of final data and of tariff lines, public/v1/preview and
public/v1/previewTariffline, and the twins of the metadata and of the availability,
public/v1/getMetadata, public/v1/getDA and public/v1/getDATariffline. Of Comtrade Tools
it wraps both operations, tools/v1/getTradeBalance and tools/v1/getBilateralData. Beside
them the list tasks answer from UN Comtrade's public reference files, packaged with this
version or fetched without the key. The fourteen operations that no task wraps yet stand here
with their public issues:
The unit values, the trade matrix and the two MBS series,
data/v1/getSUV,data/v1/getTradeMatrix,data/v1/getMBSandpublic/v1/getMBS(https://github.com/xippios/sdk-comtrade/issues/43).The ten operations of the premium Bulk and Async products, which a free key does not reach:
bulk/v1/get,bulk/v1/file,bulk/v1/getTariffline,bulk/v1/fileTariffline,bulk/v1/getClassic,bulk/v1/fileClassic, the trade matrix's filebulk/v1/fileTradeMatrix,async/v1/get,async/v1/getTarifflineandasync/v1/getDa(https://github.com/xippios/sdk-comtrade/issues/44).
A documented choice of a wrapped operation that a caller cannot make stands here with its public issue:
format, which the Help Center offers on the data operations as CSV and tab-separated text beside the default JSON: the package asks for JSON (https://github.com/xippios/sdk-comtrade/issues/45).A query of
get_trade_balanceorget_bilateral_datathat names neitherreporter_codenorpartner_code, or nocmd_code, which the Tools specs take: the tasks refuse it before it is sent, since UN Comtrade offers no count on the Tools to check a query's size first (https://github.com/xippios/sdk-comtrade/issues/72).period="recent", which the spec ofgetWorldSharelists:get_world_sharerefuses it before it is sent, since UN Comtrade answered it with HTTP 500 on every try (https://github.com/xippios/sdk-comtrade/issues/28).The
clCodeEBSDMX, which the spec ofgetTarifflinelists:get_tariffline_datacheckscl_codeagainst the packagedclCodelist, which lacks it, sincegetDaand both Tools answered it with HTTP 400; no recording showsgetTarifflineanswering it (https://github.com/xippios/sdk-comtrade/issues/29).
What the package adds is the count before get_data, the calls of 12 periods that
get_data sends a longer list of periods in, joining their rows, the check of each code
against the packaged lists, and of each product code against its classification file, before
a keyed request and the names of the codes in meta.names. It fixes no filter and ranks
nothing for the caller, and joins no series but the calls of one get_data call: the five
tasks of 0.3.0 that fixed a filter, ranked or joined a series of their own left in 0.4.0, and
the query of each stays one get_data or get_bilateral_data call with the arguments that
it fixed. What the package observed of UN Comtrade that its documentation
does not say, each note with its probe, stands in docs/upstream/OBSERVED.md.
Related MCP server: @cyanheads/un-comtrade-mcp-server
Install
uv add xippios-comtrade # client only
uv add "xippios-comtrade[mcp]" # + MCP server
uv add "xippios-comtrade[http]" # + FastAPI routerSet COMTRADE_API_KEY in the environment. Nothing is read from files. The public
operations (get_comtrade_releases, get_world_share, the five tasks named _preview) and
the reference files need no key and send none.
30-second example
from xippios.comtrade import count_data, get_data
# Switzerland (reporter 757) exports to the World (partner 0) in 2023, all products.
query = {
"reporter_code": "757",
"period": "2023",
"partner_code": "0",
"cmd_code": "TOTAL",
"flow_code": "X",
}
count_data("C", "A", "HS", **query).data # 32: every customs procedure and mode of transport
result = get_data("C", "A", "HS", **query)
total = next(r for r in result.data if (r.customs_code, r.mot_code) == ("C00", 0))
total.primary_value # Decimal('419922543423.509'); JSON: a number
result.meta.endpoint, result.meta.request # 'data/v1/get', the arguments above
# Several codes are a list, sent as reporterCode=757,842: one count for both reporters.
count_data("C", "A", "HS", **{**query, "reporter_code": [757, 842]})Parameters are upstream's (typeCode, reporterCode, ...) in snake_case and take
upstream's codes. Several values of one filter are a list, ["757", "842"] or
[757, 842], which the package sends as upstream takes them, 757,842; a comma-separated
text is refused before any request. Reporter and partner codes are UN Comtrade's, not ISO
numeric: Switzerland is 757. Every argument is checked before the call, in the order of
the arguments, and the first problem is the refusal: coded ones (type_code, cl_code,
flow_code, customs_code, mot_code, aggregate_by, breakdown_mode) against the
lists packaged from upstream's reference files and spec (list_codes gives each value
with upstream's words for it where a reference file words it, freq_code's from
Frequency.json), reporter_code against the packaged copy of upstream's
Reporters.json (reference/Reporters.json) and partner_code and partner2_code
against that of partnerAreas.json, the others by shape. A code that its packaged list
lacks raises UnknownCode, an InvalidRequestError naming the list, its fetch date and
the closest codes (756 names 757, Switzerland; C16 names C15, Relief
consignments); any other problem raises InvalidRequestError. Each refusal before a
request says that nothing was sent. Once every argument passed, cmd_code is checked
against the classification file of cl_code, the file that list_commodities lists,
fetched without the key once per process: a code that the file lacks, or a wildcard that
begins none of its codes, raises InvalidRequestError naming the closest codes and
saying that the file alone was asked for. TOTAL and AG1 to AG6 read no file, nor
does ALL, every product code, which count_data and get_data take, and BE and TM,
which have none, keep the check by shape. count_data and get_data refuse before the
call every HS edition, cl_code="H0" to "H6", which UN Comtrade answered with HTTP 500
wherever a reporter used it, naming "HS", whose rows carry each reporter's edition,
get_tariffline_data refuses "H6", which its operation answered so too, and every task that takes freq_code and period refuses a month with freq_code="A" or a
year with "M", which UN Comtrade answers with no row. get_world_share refuses
period="recent", which it answered with HTTP 500 on every try. Every answer names the codes it was called with and
the reporter, partner, flow, customs, transport, supply, unit and frequency codes of its
rows in meta.names, by the packaged lists, so an answer without rows names what the
call asked for.
from xippios.comtrade import (
list_classifications,
list_codes,
list_commodities,
list_partners,
list_reporters,
)
list_reporters().data # 256 reporters, packaged with this version: no call
list_reporters(search="switz").data # code, ISO alpha-3 or name, any case: 757
list_partners().data # 310 partner areas, 0 World among them
list_commodities("HS", search="coffee").data # from 8,262 HS codes, fetched keyless once
list_codes("motCode").data[3] # MotCodeValue(mot_code='2100', text='Sea'): packaged
list_classifications(category="cmd:H6").data[0].variable # 'Product [HS 2022]': the indexRelease dates are per dataset, so they sit on the rows, not in meta.published_at.
Upstream prints first_released, last_released, publication_date and date_release
without a zone, so they are naive datetimes:
from xippios.comtrade import (
get_comtrade_releases,
get_data_availability,
get_live_update,
get_metadata,
get_world_share,
)
[dataset] = get_data_availability("C", "A", "HS", reporter_code="757", period="2023").data
dataset.first_released, dataset.last_released # first publication and latest revision
notes = get_metadata("C", "A", "HS", reporter_code="757", period="2023").data[0].notes
[note.publication_date for note in notes] # "New Data", then each "Revised Data"
get_live_update().data # the 50 most recent releases, newest first
get_comtrade_releases().data # upstream's recent releases (newest first when recorded); keyless
[share] = get_world_share("C", "A", reporter_code="757", period="2023").data # keyless
share.world_share, share.last_released # Decimal('0.01651852126450239'), its releaseWithout a key, the public previews answer one period and one product code a call, at most
500 records, and the public twins of the metadata and the availability answer what the keyed
tasks answer. list_trade_data_items says what each column of the data means, from the
packaged TradeDataItems.json, without a call:
from xippios.comtrade import (
get_data_availability_preview,
get_data_preview,
get_tariffline_availability_preview,
get_tariffline_data_preview,
list_trade_data_items,
)
ch = {"reporter_code": "757", "period": "2023"} # one period: a second is refused
world = {"partner_code": "0", "cmd_code": "TOTAL", "flow_code": "X"}
[total] = get_data_preview("C", "A", "HS", **world, **ch).data # the total row alone
total.primary_value # Decimal('419922543423.509'), as get_data's total row
coffee = get_tariffline_data_preview(
"C", "A", "HS", partner_code="76", cmd_code="090111", flow_code="M", **ch
).data # 47 rows of Brazil's coffee, about twelve for each of four modes of transport
[dataset] = get_data_availability_preview("C", "A", "HS", **ch).data # as get_data_availability
[lines] = get_tariffline_availability_preview("C", "A", "HS", **ch).data
lines.total_records, lines.length_cmd_code # 2955451 records; product codes of 6 digits
[item.description for item in list_trade_data_items().data if item.data_item == "primaryValue"]get_metadata_preview answers as get_metadata with reporter_code or period, and without
either every reporter's every dataset, 5,490 for annual HS goods, about 5 MB.
With the key, get_tariffline_data takes up to 12 periods and every filter at once, with
include_desc and max_records, and get_tariffline_availability takes the publication
dates. No count comes first, since UN Comtrade's countOnly counted 10 records for these 47
tariff lines: meta.total stays None, and an answer of max_records rows, or of 100,000,
the most one call serves, carries a note that the query may hold more:
from xippios.comtrade import get_tariffline_availability, get_tariffline_data
ch = {"reporter_code": "757", "period": "2023"}
coffee = {"partner_code": "76", "cmd_code": "090111", "flow_code": "M", **ch}
lines = get_tariffline_data("C", "A", "HS", **coffee, include_desc=True)
sorted({row.mot_desc for row in lines.data}) # ['Air', 'Inland waterway', 'Railway', 'Road']
get_tariffline_data("C", "A", "HS", **coffee, max_records=5).meta.notes # may hold more
published = {"published_date_from": "2024-01-01", "published_date_to": "2024-12-31"}
[dataset] = get_tariffline_availability("C", "A", "HS", reporter_code="757", **published).data
dataset.period, dataset.total_records # 2023, 2955451: Switzerland's tariff lines of 2023Two Tools operations, which upstream's spec marks "EXPERIMENTAL - USE SPARINGLY", put exports beside imports and a reporter's figures beside its partners' mirror figures:
from xippios.comtrade import get_bilateral_data, get_trade_balance
ch = {"reporter_code": "757", "period": "2023", "cmd_code": "TOTAL"}
[row] = get_trade_balance("C", "A", "HS", partner_code="0", breakdown_mode="classic", **ch).data
row.primary_value_x, row.primary_value_m # Switzerland's 2023 exports and imports
row.primary_value_bal # upstream's "X - M", as sent
bilateral = get_bilateral_data("C", "A", "HS", partner_code="842", flow_code="X", **ch).data
bilateral.note # upstream's data-gap note: 'EXPERIMENTAL: We have good news! ...'
[row] = bilateral.data
row.primary_value, row.mirror_primary_value # exports to the USA; the USA's importsBoth need reporter_code or partner_code, and cmd_code, since upstream offers no
count to check a query's size first, and refuse a query without them before it is sent,
saying that nothing was sent. A mirror of 0 is no sign of no trade: the mirror
depends on whether the partner reported. So get_bilateral_data returns upstream's
note, which counts the partners with a data gap without naming them, and its
timestamp_requested, with the rows: its data is one BilateralData, not a list.
get_data counts first with upstream's countOnly, so one call sends two keyed requests,
after the classification file of a product code, fetched without the key once per process:
at most 3 requests, each tried at most 4 times. A count of zero returns an empty result
with a note that UN Comtrade counted no record, without the data request, and a count
above 100,000 raises core's QueryTooLarge
(xippios.core.QueryTooLarge) with the count before any data is fetched, because upstream
would cut the answer at 100,000 rows without saying so; meta.total is the count. With
max_records, upstream's maxRecords, the count still comes first, a count above it is no
refusal, and a note says that the rows are a sample of the query.
UN Comtrade takes at most 12 periods a call, and get_data takes up to 120: it sends a
longer list in calls of 12, in the order given, and counts every call before it fetches any,
so a total above 100,000 raises QueryTooLarge with each call's count before any data is
fetched, and a call that counts 0 is not fetched. The rows come call after call, each call's
in upstream's order.
meta.total stays None, since no count of UN Comtrade's counts the
whole list, and meta.notes names the periods that no row holds: a period that UN Comtrade
has not released answers no row, as a period without trade does. A call after the first that
fails raises its error naming the periods answered before it, and nothing is returned.
aggregate_by naming period and max_records, which one call alone answers, are refused
before any request past 12 periods; count_data and get_trade_balance take 12. A period
listed twice is refused before any request, in a list of any length, since past 12 periods
its calls would return its rows twice.
years = [str(year) for year in range(2010, 2024)] # 14 years: calls of 12 and of 2
series = get_data("C", "A", "HS", **{**query, "period": years}, breakdown_mode="classic")
sorted(row.period for row in series.data) # one total row a year, '2010' to '2023'
series.meta.total, series.meta.notes # None, and [] where every year holds a rowcount_data and get_data take mos_code, a service's mode of supply, "0" to "4", the
values a recording shows filtering, and refuse any other before the call. The client keeps
the reference files for the life of the process and the keyed answers for
five minutes, so a repeated call spends no call of the daily quota. A free key allows 1
call per second and 500 calls per day, and countOnly calls count; the client spaces
calls 1.5 s apart (upstream's gateway refuses some calls spaced exactly 1 s apart) and
counts no calls, so the daily quota is yours to track: once upstream answers that it is
spent, the client sends no keyed call until the time upstream names and raises
RateLimitError instead, while the keyless operations and reference files, which spend
none of it, go on.
MCP
{
"mcpServers": {
"comtrade": {
"command": "uvx",
"args": ["--from", "xippios-comtrade[mcp]", "xippios-comtrade-mcp"],
"env": { "COMTRADE_API_KEY": "..." }
}
}
}Tools are read-only and named comtrade_<verb>_<noun>. Results are capped at
200 rows or 64 KB with a note on how to narrow the query; comtrade_list_reporters and
comtrade_list_partners have a cap of their own, 400 rows or 100 KB, so their whole
tables reach the agent. comtrade_list_commodities has the same cap, but a
classification is larger (8,262 HS codes), so its note says to search. All three take
search: {"search": "switz"} returns 757 Switzerland. comtrade_get_world_share has a cap
of 400 rows or 150 KB, so one period for every reporter (214 rows for 2023) reaches the
agent whole; its note says to narrow by reporter_code or period. A filter of several values
takes a JSON array, {"reporter_code": [757, 842]}. --http serves streamable HTTP
instead of stdio. --split-periods PERIODS, 1 to 120 and 24 by default, is the most periods
one comtrade_get_data call takes; at 24, two calls of 12, it sends at most 4 keyed
requests, the count and the data of each, and the classification file of a product code
without the key; the setting holds for the whole process. The FastAPI router serves each task at
/comtrade/<task>, as a GET with query parameters, or as a POST with a JSON body where
the task takes a list.
Status
Upstream operation | Task function | MCP tool | Status |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha; experimental upstream |
|
|
| alpha; experimental upstream |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
|
|
| alpha |
The package covers these twenty-two tasks and requires xippios-core 0.5.x (~=0.5.0); 0.3.0
does not work with core 0.5.0. The slices get_bilateral_flows, get_world_trade and
get_mirror_flows, the ranking get_top_partners and get_commodity_series, which 0.3.0
served, left after it: a task of a source fixes no filter, sort, rank or cut for the
caller, and get_data and get_bilateral_data answer the same rows with the arguments
that those five fixed. Alpha: the public surface may change in a minor version before
1.0; CHANGELOG.md lists every change.
Upstream terms and attribution
Data comes from UN Comtrade (https://comtrade.un.org), on the terms upstream states
for it in its Policy on Comtrade Data Use,
under which use of the data is subject to a license agreement found at
https://comtrade.un.org/en/license-agreement, regardless of whether the data is accessed via
free or premium access; this package adds no rights to it.
Documentation snapshot and its attribution: docs/upstream/FETCHED.md.
Workflows
ci.yml runs ruff, its format check, mypy, pytest and pre-commit on Python 3.12, 3.13 and
3.14, requires a changelog entry of every pull request but Dependabot's and refuses a
fixture file over 256 KiB that a pull request adds or changes. It runs on every pull request and,
called by publish.yml, once for a release, and its job ci is the check the
organization's ruleset requires. It is handed no secret, and no variable switches it off.
publish.yml is the release train (conventions §12): on a push to main whose
pyproject.toml names a version that has no tag yet and has its section in CHANGELOG.md,
it runs ci.yml, refuses a core pinned to git, tags the merge commit, builds the package
and, once a reviewer of the environment pypi approves the run, publishes it to PyPI by
trusted publishing. Every push to main and a dispatch start it, and a push that brings no
release ends quietly. It is handed no secret: the step that tells a release is handed the
job's token as GH_TOKEN, the tag goes with the job's token and PyPI trusts the workflow
itself. Its job tag holds the one checkout of the repository that keeps its credentials,
since it pushes the tag with the job's token; every other checkout sets
persist-credentials: false (conventions §13). No variable switches it off.
live.yml runs every live test against the upstream with --tb=short --assert=plain, so
its public log holds neither a failing test's arguments nor the values an assertion compared.
It runs every night at 05:31 UTC and on demand, never on a pull request.
Its pytest step alone is handed XIPPIOS_LIVE_TESTS and, each from the secret of the same
name, COMTRADE_API_KEY, so the checkout, setup-uv and uv sync see none.
A variable WORKFLOW_LIVE of off, the repository's over the organization's, switches it off.
conventions.yml calls the organization's review of a pull request against the documents
listed under Documents below, the check conventions / conventions, when a pull request
opens, is pushed to, reopens or is edited, and on a push to main or a dispatch the review
of the range of commits, range / range. It hands the review the organization's
secret of the model's key, by name. A variable WORKFLOW_CONVENTIONS of off, the
repository's over the organization's, switches both off.
adr-index.yml calls the organization's check of the ADR index, adr-index / adr-index,
which runs scripts/adr_index.py --check, when a pull request opens, is pushed to or
reopens. It hands over nothing, and the called workflow reads its switch itself: a variable
WORKFLOW_ADR_INDEX of off, the repository's over the organization's, skips the check.
Documents
sdk-core: docs/conventions.md — the conventions every xippios source package follows: its layout, names, results, tests and releases.
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-comtrade: docs/adr.md — the index of this package's own decisions, generated from the records in
docs/adr/.sdk-comtrade: docs/upstream/FETCHED.md — the snapshot of the upstream documentation, the reference for names, parameters and semantics.
sdk-comtrade: docs/upstream/OBSERVED.md — what UN Comtrade was observed to answer that the snapshot does not state, each note with its probe.
Licence
Apache-2.0. See LICENSE.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
UN Comtrade international trade statistics via MCP. Country/HS lookups, flows, balances, rankings.
Comtrade MCP — UN Comtrade API for international bilateral trade data
Trade Intel MCP — Compound tools that chain Comtrade, Census, Treasury,
Read authorized Loam tables and supported external databases through a bounded MCP connection.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceProvides access to UN Comtrade international bilateral trade data via an MCP server, enabling AI agents to query trade statistics through natural language.88 npmMIT
- AlicenseNot gradedqualityBmaintenanceAccess UN Comtrade international merchandise and services trade statistics via MCP tools for country lookups, HS commodity search, bilateral trade flows, balances, rankings, and data availability.459 npm5Apache 2.0
- AlicenseAqualityCmaintenanceEnables querying Brazilian foreign trade data through MCP tools for trade flows, freight costs, code resolution, and dataset caveats, with known data defects corrected in responses.4MIT
- FlicenseNot gradedqualityDmaintenanceEnables secure, read-only querying of only predefined logical database views through MCP tools and a REST API, using validated SQL and semantic view metadata.-