io.github.cyanheads/un-comtrade-mcp-server
UN Comtrade international trade statistics via MCP. Country/HS lookups, flows, balances, rankings.
ماذا يمكنك أن تفعل مع io.github.cyanheads/un-comtrade-mcp-server؟
- 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 set - Parallel 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 present - Description enrichment — joins country and HS/EBOPS names from the reference cache, covering the preview endpoint's omission of
*Descfields truncated: trueplus a recovery hint when a public preview response reaches 500 recordsisReportedflag on trade flow records distinguishes directly-reported values from UN-estimated/aggregated rowsvalidAsReporteron country lookups prevents constructing invalid queries with partner-only area codes
التثبيت
أضف هذا إلى إعدادات MCP في عميلك (Claude Desktop: claude_desktop_config.json، وCursor: .cursor/mcp.json، ويستخدم VS Code وغيره الصيغة نفسها «mcpServers»).
claude mcp add --transport http un-comtrade-mcp-server 'https://un-comtrade.caseyjhand.com/mcp'
{
"mcpServers": {
"un-comtrade-mcp-server": {
"type": "http",
"url": "https://un-comtrade.caseyjhand.com/mcp"
}
}
}
@cyanheads/un-comtrade-mcp-serverclaude mcp add un-comtrade-mcp-server -e 'COMTRADE_SUBSCRIPTION_KEY=<COMTRADE_SUBSCRIPTION_KEY>' -e 'MCP_LOG_LEVEL=info' -- npx -y @cyanheads/un-comtrade-mcp-server@0.2.0
{
"mcpServers": {
"un-comtrade-mcp-server": {
"command": "npx",
"args": [
"-y",
"@cyanheads/un-comtrade-mcp-server@0.2.0"
],
"env": {
"COMTRADE_SUBSCRIPTION_KEY": "<COMTRADE_SUBSCRIPTION_KEY>",
"MCP_LOG_LEVEL": "info"
}
}
}
}
متغيرات البيئة
COMTRADE_SUBSCRIPTION_KEYAzure API Management key from comtradedeveloper.un.org. Optional — without it, tools fall back to the public preview endpoint (500-record cap).MCP_LOG_LEVELSets the minimum log level for output (e.g., 'debug', 'info', 'warn').
@cyanheads/un-comtrade-mcp-serverclaude mcp add un-comtrade-mcp-server -e 'MCP_TRANSPORT_TYPE=<MCP_TRANSPORT_TYPE>' -e 'MCP_HTTP_HOST=127.0.0.1' -e 'MCP_HTTP_PORT=3010' -e 'MCP_HTTP_ENDPOINT_PATH=/mcp' -e 'MCP_AUTH_MODE=none' -e 'MCP_LOG_LEVEL=info' -- npx -y @cyanheads/un-comtrade-mcp-server@0.2.0
{
"mcpServers": {
"un-comtrade-mcp-server": {
"command": "npx",
"args": [
"-y",
"@cyanheads/un-comtrade-mcp-server@0.2.0"
],
"env": {
"MCP_TRANSPORT_TYPE": "<MCP_TRANSPORT_TYPE>",
"MCP_HTTP_HOST": "127.0.0.1",
"MCP_HTTP_PORT": "3010",
"MCP_HTTP_ENDPOINT_PATH": "/mcp",
"MCP_AUTH_MODE": "none",
"MCP_LOG_LEVEL": "info"
}
}
}
}
متغيرات البيئة
MCP_TRANSPORT_TYPESelects the HTTP transport.MCP_HTTP_HOSTThe hostname for the HTTP server.MCP_HTTP_PORTThe port to run the HTTP server on.MCP_HTTP_ENDPOINT_PATHThe endpoint path for the MCP server.MCP_AUTH_MODEAuthentication mode to use: 'none', 'jwt', or 'oauth'.MCP_LOG_LEVELSets the minimum log level for output (e.g., 'debug', 'info', 'warn').
التوثيق
مأخوذ من ملف README للمشروع على GitHub ويُحدَّث أسبوعيًا. تفتح الروابط على GitHub.
المحتويات
@cyanheads/un-comtrade-mcp-server
Access UN Comtrade international merchandise and services trade statistics — country lookups, HS commodity search, bilateral trade flows, balances, rankings, and data availability — via MCP. STDIO or Streamable HTTP.
9 Tools • 2 Resources
Public Hosted Server: https://un-comtrade.caseyjhand.com/mcp
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.
Tools
| Tool | Description |
|---|---|
comtrade_lookup_countries | Resolve country and area names to Comtrade M49 numeric codes. |
comtrade_search_commodities | Find HS commodity codes by keyword, description, or code prefix. |
comtrade_list_service_categories | List EBOPS 2010 service trade categories by keyword or parent code. |
comtrade_get_trade_flows | Fetch bilateral trade flow records — value, quantity, and weight per period/commodity/partner. |
comtrade_get_trade_balance | Compute a country's trade balance (exports minus imports) across one or more periods. |
comtrade_get_top_partners | Rank trading partners by trade value for a reporter, commodity, and flow direction. |
comtrade_get_top_commodities | Rank commodity categories by trade value for a reporter and flow direction. |
comtrade_get_data_availability | Check which reporter/period/classification combinations have published data. |
comtrade_get_services_trade | Fetch international trade-in-services data (EBOPS 2010). |
Resources
| Resource | Description |
|---|---|
comtrade://countries | Complete country/area code list with M49 codes, ISO identifiers, and reporter validity. |
comtrade://hs-classification/{level} | 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.
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 results- Reference 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–H6 aggr_levelnarrows to2(chapter),4(heading), or6(subheading); omit for all levelslimitdefaults to 50; values above 200 return all matches.truncated: truewhen matches exceed a smaller 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_code limitdefaults to 100; values above 500 return all categories.truncated: truewhen matches exceed a smaller limit- Returned
idis theservice_codeforcomtrade_get_services_trade
comtrade_get_trade_flows tool
- Requires
reporter_code,flow_code(Mimport /Xexport /RXre-export /RMre-import), andperiodvalues (YYYYorYYYYMM). Up to 120 periods are accepted but only the first 12 are served; the rest are listed inunservedPeriods partner_code: 0returns the World total; omit it for a per-partner breakdown.classificationsupportsHS,H0–H6, and SITCS1–S4/SS(commodity search is HS-only)cmd_code[]accepts up to 200 codes and serves the first 20, listing the rest inunservedCmdCodes; omit it or pass["TOTAL"]for cross-commodity totals.truncated: trueplustruncationHintmeans the response hit the 500-record cap;isReportedseparates directly reported rows from UN-estimated ones
comtrade_get_trade_balance tool
- Returns
balanceUsd(signed),exportsUsd,importsUsd, andcoverageRatio(exports / imports) per period. Optionalcmd_code[]restricts the balance to HS or SITC commodities - Serves 12 periods and 20 codes per call (accepts up to 120 and 200), listing the rest in
unservedPeriods/unservedCmdCodes. Anoticewarns when either flow hit the 500-record cap and the balance may be incomplete mirrorCaveaton every response: the balance reflects this reporter's own values, not the partner's mirror data
comtrade_get_top_partners tool
- Takes one
reporter_code,flow_code(M/X), and singleperiod; optional singlecmd_code(omit for total merchandise trade) - Returns up to
limitpartners (default 10; above 50 returns all retrieved), each withrank,primaryValueUsd, andsharePercent truncated: truewhen the fetch hit the 500-record cap
comtrade_get_top_commodities tool
- Takes one
reporter_code,flow_code, and singleperiod;aggr_levelis2(HS chapter, default) or4(heading).partner_codedefaults to World (0); set it to scope to one partner - Returns up to
limitcategories (default 10; above 50 returns all retrieved), each withrank,primaryValueUsd, andsharePercent truncated: truewhen the 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(omitted or blank resolves toHSfor goods,EB10for services) - Returns per-dataset
totalRecords,firstReleased, andlastReleasedwhere available; omit all filters to browse goods availability - Annual data typically publishes 3–12 months after the reference year — call this before querying recent periods
comtrade_get_services_trade tool
- Same inputs as
comtrade_get_trade_flows:reporter_code,flow_code(M/X),periodvalues, optionalpartner_code(0for all partners combined). Serves the first 12 of up to 120 periods, listing the rest inunservedPeriods service_codefilters to one EBOPS category; resolve it withcomtrade_list_service_categoriestruncated: trueplustruncationHintwhen the response hit the 500-record cap. Country and period coverage is more limited than for goods
comtrade://countries resource
- Complete country/area list as
application/json— M49 code, ISO identifiers,validAsReporter, andisGroup - Loaded 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 error- Returns 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 set - Parallel 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 present - Description 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 when a public preview response reaches 500 recordsisReportedflag 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
Public Hosted Instance
A public instance is available at https://un-comtrade.caseyjhand.com/mcp — no installation required. It runs on the keyless public preview endpoint (500 records per upstream request), splitting served periods into paced requests at least one second apart. Balance needs two requests per period, so longer arrays take more time. Point any MCP client at it via Streamable HTTP:
{
"mcpServers": {
"un-comtrade-mcp-server": {
"type": "streamable-http",
"url": "https://un-comtrade.caseyjhand.com/mcp"
}
}
}
Self-Hosted / Local
Prerequisites: A UN Comtrade subscription key is optional. Without one, tools use the public preview endpoint (500 records per upstream request). A key selects authenticated access; retrieval and request limits depend on UN Comtrade and the subscription.
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/mcp
Prerequisites
- Bun v1.4.0 or higher (or Node.js v24+). Development and Docker images use Bun 1.4.3.
- Optional: a UN Comtrade subscription key for authenticated API access subject to subscription limits. Without one, data tools use the public preview endpoint (500 records per upstream request). 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.git
- Navigate into the directory:
cd un-comtrade-mcp-server
- Install dependencies:
bun install
- Configure environment:
cp .env.example .env
# edit .env and set COMTRADE_SUBSCRIPTION_KEY if you have one
Configuration
All configuration is validated at startup via Zod schemas in src/config/server-config.ts.
| Variable | Description | Default |
|---|---|---|
COMTRADE_SUBSCRIPTION_KEY | Azure API Management subscription key from comtradedeveloper.un.org. Without it, tools use the public preview endpoint (500-record cap). | — |
COMTRADE_API_BASE_URL | Override the Comtrade API base URL. | https://comtradeapi.un.org |
MCP_TRANSPORT_TYPE | Transport: stdio or http. | stdio |
MCP_HTTP_PORT | HTTP server port. | 3010 |
MCP_HTTP_ENDPOINT_PATH | HTTP endpoint path. | /mcp |
MCP_PUBLIC_URL | Public origin override for reverse-proxy deployments. | — |
MCP_SESSION_MODE | HTTP session mode: auto, stateful, or stateless. | stateless |
MCP_AUTH_MODE | Auth mode: none, jwt, or oauth. | none |
MCP_LOG_LEVEL | Log level (debug, info, warning, error). | info |
LOGS_DIR | Directory for log files (Node.js only). | <project-root>/logs |
LOG_TOOL_FAILURE_PAYLOADS | Log failed tool arguments and results, redacted by key name, capped at LOG_TOOL_FAILURE_PAYLOAD_MAX_BYTES (default 16384). Secrets inside free-form values are not redacted. | false |
STORAGE_PROVIDER_TYPE | Storage backend: in-memory, filesystem, supabase, cloudflare-kv/r2/d1. | in-memory |
OTEL_ENABLED | Enable OpenTelemetry instrumentation. | false |
OTEL_EXPORTER_OTLP_ENDPOINT | OTLP base URL for traces (/v1/traces) and metrics (/v1/metrics). | — |
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT | Opt-in OTLP log endpoint, used as-is. | — |
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:http - Run 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-server
The 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 |
|---|---|
src/index.ts | createApp() entry point — registers tools, resources, and inits services. |
src/config | Environment variable parsing and validation with Zod. |
src/mcp-server/tools | Tool definitions (*.tool.ts). Nine tools across reference resolution, trade data, and workflow aggregations. |
src/mcp-server/resources | Resource definitions (*.resource.ts). Country list and HS hierarchy resources. |
src/services/comtrade-data | ComtradeDataService — authenticated/preview request builder with retry and key fallback. |
src/services/comtrade-reference | ComtradeReferenceService — reference data loader (countries, HS, EBOPS), startup cache, keyword search. |
src/services/comtrade-meta | ComtradeMetaService — data availability and dataset metadata endpoints. |
tests/ | Unit and integration tests mirroring src/. |
Development guide
See CLAUDE.md for development guidelines and architectural rules. The short version:
- Handlers throw, framework catches — no
try/catchin tool logic - Use
ctx.logfor request-scoped logging,ctx.statefor tenant-scoped storage - Register new tools and resources via the barrels in
src/mcp-server/*/definitions/index.ts - Wrap 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
Use UN Comtrade data in accordance with the UN Comtrade license agreement, including its redistribution terms.
Contributing
Issues are welcome. Run checks and tests before submitting:
bun run devcheck
bun run test
License
Apache-2.0 — see LICENSE for details.
الأسئلة الشائعة
ما هو io.github.cyanheads/un-comtrade-mcp-server؟
UN Comtrade international trade statistics via MCP. Country/HS lookups, flows, balances, rankings.
كيف أثبّت io.github.cyanheads/un-comtrade-mcp-server؟
يعمل كخادم بعيد. في Claude Code: claude mcp add --transport http un-comtrade-mcp-server 'https://un-comtrade.caseyjhand.com/mcp'. وفي العملاء الآخرين، الصق إعداد JSON من هذه الصفحة في إعدادات MCP الخاصة بهم.
هل يحتاج io.github.cyanheads/un-comtrade-mcp-server إلى مفتاح API؟
لا يذكر إدراجه في السجل أي مفتاح أو سر إلزامي. قد تتطلب بعض الميزات حسابًا لدى الخدمة التي يتصل بها.
هل io.github.cyanheads/un-comtrade-mcp-server مفتوح المصدر؟
نعم. شيفرته متاحة على GitHub بترخيص Apache-2.0.
من يصون io.github.cyanheads/un-comtrade-mcp-server؟
ينشره cyanheads. يدرجه AI.tn لكنه لا يصونه ولا يوصي به.
من سجل MCP الرسمي. الإدراج ليس توصية: راجع شيفرة الخادم وصلاحياته قبل منحه الوصول إلى بياناتك.