@cyanheads/un-comtrade-mcp-server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@@cyanheads/un-comtrade-mcp-serverGet top trading partners for Germany in 2023"
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.
Overview
International merchandise and services trade statistics from UN Comtrade. Resolve country and HS commodity codes, fetch bilateral trade flows and services trade, and compute balances, partner/commodity rankings, and data availability from any MCP client. Runs as a stdio process or a local Streamable HTTP server.
Tools
Tool | Description |
| Resolve country and area names to Comtrade M49 numeric codes. |
| Find HS commodity codes by keyword, description, or code prefix. |
| List EBOPS 2010 service trade categories by keyword or parent code. |
| Fetch bilateral trade flow records — value, quantity, and weight per period/commodity/partner. |
| Compute a country's trade balance (exports minus imports) across one or more periods. |
| Rank trading partners by trade value for a reporter, commodity, and flow direction. |
| Rank commodity categories by trade value for a reporter and flow direction. |
| Check which reporter/period/classification combinations have published data. |
| Fetch international trade-in-services data (EBOPS 2010). |
Resources
Resource | Description |
| Complete country/area code list with M49 codes, ISO identifiers, and reporter validity. |
| Top-level HS commodity hierarchy at chapter, heading, or subheading level. |
Both resources are also reachable via tools — comtrade_lookup_countries and comtrade_search_commodities cover the same data with keyword search.
Related MCP server: worldbank-mcp-server
Capability reference
comtrade_lookup_countries tool
Accepts a partial or full country name, or an ISO alpha-2/alpha-3 code;
rolefilters to"reporter","partner", or"any"(default)validAsReporterflag on each match — regional groupings (e.g. World, EU) are valid partners but not valid reportersinclude_groups(defaulttrue) toggles regional/economic groupings in the resultsReference data loads from UN static files at startup — no subscription key required, instant response
comtrade_search_commodities tool
Free-text keyword, partial description, or code-prefix search;
classificationselectsHS(combined dataset, default) or a specific editionH0–H6aggr_levelnarrows to2(chapter),4(heading), or6(subheading); omit for all levelsUp to 200 results per call (
limit, default 50);truncated: truewhen matches exceed the limitrecommendedQueryCodeon each result — the best code to pass ascmd_codein trade queries
comtrade_list_service_categories tool
Lists EBOPS 2010 service categories, optionally filtered by keyword or
parent_codeUp to 500 results per call (
limit, default 100);truncated: truewhen matches exceed the limitReturned
idis theservice_codeforcomtrade_get_services_trade
comtrade_get_trade_flows tool
Requires
reporter_code,flow_code(Mimport /Xexport /RXre-export /RMre-import), and 1–12periodvalues (YYYYorYYYYMM)partner_code: 0aggregates all partners (World total); omit for a per-partner breakdowncmd_code[]accepts up to 20 HS codes; omit or pass"TOTAL"for cross-commodity totalsFree-tier cap of 500 records per call;
truncated: trueplus atruncationHintwhen the cap is hitisReportedflags directly-reported rows vs. UN-estimated/aggregated ones; joins country and commodity descriptions from the startup reference cache
comtrade_get_trade_balance tool
Runs export (
X) and import (M) fetches in parallel per period, then computes the balance locallyReturns
balanceUsd(signed),exportsUsd,importsUsd, andcoverageRatio(exports / imports) per periodOptional
cmd_code[](up to 20) restricts the balance to specific commoditiesmirrorCaveaton every response — the balance reflects this reporter's own values, not the mirror partner's
comtrade_get_top_partners tool
Fetches the full per-partner breakdown for one
reporter_code+flow_code(M/X) + singleperiod, then sorts locally by valueOptional single
cmd_code; omit for total merchandise tradeReturns up to
limitpartners (max 50, default 10), each withrank,primaryValueUsd, andsharePercenttruncated: truewhen the underlying fetch hit the 500-record cap
comtrade_get_top_commodities tool
Ranks commodity categories for one
reporter_code+flow_code+ singleperiodaggr_levelselects2(HS chapter, default) or4(heading); optionalpartner_codescopes to one bilateral relationshipReturns up to
limitcategories (max 50, default 10), each withrank,primaryValueUsd, andsharePercenttruncated: truewhen the underlying fetch hit the 500-record cap
comtrade_get_data_availability tool
All filters optional —
reporter_code,period,freq(A/M, defaultA),type_code(Cgoods /Sservices, defaultC),classification(defaultHS)Returns per-dataset
totalRecordsandpublicationDate; omit all filters to browse the full availability indexAnnual data typically publishes 3–12 months after the reference year — call this before querying recent periods
comtrade_get_services_trade tool
Same bilateral shape as
comtrade_get_trade_flows:reporter_code,flow_code(M/X), 1–12periodvalues, optionalpartner_code(0for all partners combined)service_codefilters to one EBOPS category; resolve it withcomtrade_list_service_categoriesFree-tier cap of 500 records per call;
truncated: trueplus atruncationHintwhen the cap is hitServices trade has more limited country and period coverage than goods trade
comtrade://countries resource
Complete country/area list as
application/json— M49 code, ISO identifiers,validAsReporter, andisGroupLoaded from the same startup reference cache
comtrade_lookup_countriessearches
comtrade://hs-classification/{level} resource
levelpath param accepts2(chapters),4(headings), or6(subheadings); any other value throws a validation errorReturns each code's
description,parent, andisLeaf; full leaf enumeration is too large to inject — usecomtrade_search_commoditiesfor keyword search
Features
Built on @cyanheads/mcp-ts-core: stdio and Streamable HTTP transports, pluggable auth (none / jwt / oauth), swappable storage (in-memory, filesystem, Supabase, Cloudflare KV/R2/D1), structured logging with optional OpenTelemetry tracing.
Comtrade-specific:
Reference data (country codes, HS hierarchy, EBOPS categories) loaded from UN static files at startup — keyword search with no per-request fetches
Authenticated (
data/v1/get) and public preview (public/v1/preview) endpoints — tools fall back to the preview endpoint when no subscription key is setParallel sub-request execution in workflow tools (
comtrade_get_trade_balanceruns export and import fetches concurrently)Retry with exponential backoff on transient failures, honoring an upstream
Retry-Afterheader when presentDescription enrichment — joins country and HS/EBOPS names from the reference cache, covering the preview endpoint's omission of
*Descfields
Agent-friendly output:
truncated: trueplus a recovery hint on any response capped at the 500-record free-tier limitisReportedflag on trade flow records distinguishes directly-reported values from UN-estimated/aggregated rowsvalidAsReporteron country lookups prevents constructing invalid queries with partner-only area codesmirrorCaveaton trade-balance output surfaces the methodological caveat without parsing error text
Getting started
Prerequisites: A UN Comtrade subscription key is optional but recommended. Without one, tools fall back to the public preview endpoint (500 records/call, lower rate limit). With a free-tier key you get the same record cap but higher request headroom.
Add the following to your MCP client configuration file.
{
"mcpServers": {
"un-comtrade-mcp-server": {
"type": "stdio",
"command": "bunx",
"args": ["@cyanheads/un-comtrade-mcp-server@latest"],
"env": {
"MCP_TRANSPORT_TYPE": "stdio",
"MCP_LOG_LEVEL": "info",
"COMTRADE_SUBSCRIPTION_KEY": "your-key-here"
}
}
}
}Or with npx (no Bun required):
{
"mcpServers": {
"un-comtrade-mcp-server": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@cyanheads/un-comtrade-mcp-server@latest"],
"env": {
"MCP_TRANSPORT_TYPE": "stdio",
"MCP_LOG_LEVEL": "info",
"COMTRADE_SUBSCRIPTION_KEY": "your-key-here"
}
}
}
}Or with Docker:
{
"mcpServers": {
"un-comtrade-mcp-server": {
"type": "stdio",
"command": "docker",
"args": [
"run", "-i", "--rm",
"-e", "MCP_TRANSPORT_TYPE=stdio",
"-e", "COMTRADE_SUBSCRIPTION_KEY=your-key-here",
"ghcr.io/cyanheads/un-comtrade-mcp-server:latest"
]
}
}
}For Streamable HTTP, set the transport and start the server:
MCP_TRANSPORT_TYPE=http MCP_HTTP_PORT=3010 COMTRADE_SUBSCRIPTION_KEY=... bun run start:http
# Server listens at http://localhost:3010/mcpPrerequisites
Bun v1.4.0 or higher (or Node.js v24+). Development and Docker images use Bun 1.4.0.
Optional: a UN Comtrade subscription key for full API access. Without one, all tools fall back to the public preview endpoint (500 records/call). Reference/lookup tools (
comtrade_lookup_countries,comtrade_search_commodities,comtrade_list_service_categories) never require a key — they query static UN reference files.
Installation
Clone the repository:
git clone https://github.com/cyanheads/un-comtrade-mcp-server.gitNavigate into the directory:
cd un-comtrade-mcp-serverInstall dependencies:
bun installConfigure environment:
cp .env.example .env
# edit .env and set COMTRADE_SUBSCRIPTION_KEY if you have oneConfiguration
All configuration is validated at startup via Zod schemas in src/config/server-config.ts.
Variable | Description | Default |
| Azure API Management subscription key from comtradedeveloper.un.org. Without it, tools use the public preview endpoint (500-record cap). | — |
| Override the Comtrade API base URL. |
|
| Transport: |
|
| HTTP server port. |
|
| HTTP endpoint path. |
|
| Public origin override for reverse-proxy deployments. | — |
| HTTP session posture: |
|
| Auth mode: |
|
| Log level ( |
|
| Directory for log files (Node.js only). |
|
| Storage backend: |
|
| Enable OpenTelemetry instrumentation. |
|
See .env.example for the full list of optional overrides.
Running the server
Local development
Build and run:
# One-time build bun run rebuild # Run the built server bun run start:stdio # or bun run start:httpRun checks and tests:
bun run devcheck # Lint, format, typecheck, security bun run test # Vitest test suite bun run lint:mcp # Validate MCP definitions against spec
Docker
docker build -t un-comtrade-mcp-server .
docker run --rm -e COMTRADE_SUBSCRIPTION_KEY=your-key -p 3010:3010 un-comtrade-mcp-serverThe Dockerfile defaults to HTTP transport, stateless session mode, and logs to /var/log/un-comtrade-mcp-server. OpenTelemetry peer dependencies are installed by default — build with --build-arg OTEL_ENABLED=false to omit them.
Project structure
Directory | Purpose |
|
|
| Environment variable parsing and validation with Zod. |
| Tool definitions ( |
| Resource definitions ( |
|
|
|
|
|
|
| Unit and integration tests mirroring |
Development guide
See CLAUDE.md for development guidelines and architectural rules. The short version:
Handlers throw, framework catches — no
try/catchin tool logicUse
ctx.logfor request-scoped logging,ctx.statefor tenant-scoped storageRegister new tools and resources via the barrels in
src/mcp-server/*/definitions/index.tsWrap external API calls: validate raw → normalize to domain type → return output schema; never fabricate missing fields
Reference data (countries, HS codes) joins must pull from the startup cache, not per-request fetches
Data license
The UN Comtrade license agreement (§5) prohibits redistributing data without prior written UN permission. Connect with your own Comtrade subscription key.
Contributing
Issues are welcome. Run checks and tests before submitting:
bun run devcheck
bun run testLicense
Apache-2.0 — see LICENSE for details.
This server cannot be deployed
Maintenance
Related MCP Connectors
Comtrade MCP — UN Comtrade API for international bilateral trade data
Trade Intel MCP — Compound tools that chain Comtrade, Census, Treasury,
Census Trade MCP — US Census Bureau International Trade data
Brazilian foreign trade, crop and commodity data as a remote MCP server. Exports and imports from MDIC/ComexStat since 2000, by HS code (SH4/SH6/NCM) and partner country, in USD FOB and kilograms — plus crop production, supply-and-demand balances, climate readings and production forecasts for hubs such as soybean, coffee, corn, beef and cocoa. Every comparison is like-for-like: two windows of equal length, each labelled with the period it actually measures, and every answer names its window and its source. 15 read-only tools, metered in credits. Nothing to install: Streamable HTTP at https://mcp.kyrodata.com/mcp with a bearer key or OAuth 2.1 (PKCE). Official registry: com.kyrodata/kyrodata.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceProvides access to UN Comtrade international bilateral trade data via an MCP server, enabling AI agents to query trade statistics through natural language.137 npmMIT
- AlicenseNot gradedqualityAmaintenanceEnables querying 29,500+ World Bank development indicators for 200+ countries across 60+ years via MCP, with 7 tools for browsing topics, sources, countries, and indicators.148 npm3Apache 2.0
- AlicenseNot gradedqualityAmaintenanceProvides macroeconomic data (GDP, inflation, unemployment, trade) for any country via MCP tools, sourced from World Bank and US BLS, no API keys required.MIT
- FlicenseNot gradedqualityCmaintenanceMCP server that provides access to UK trade data from the ONS Trade Data API, enabling queries for trade statistics, metadata, and raw data.-