Un Comtrade Mcp Server

io.github.cyanheads由 GitHub 帳號 cyanheads 發布v0.3.1更新於 Nov 5, 2026

UN Comtrade international trade statistics via MCP. Country/HS lookups, flows, balances, rankings.

已驗證Streamable HTTP可網頁執行金融資料與分析

概覽

AI 產生的概覽

UN Comtrade 貿易統計 MCP 伺服器,讓助理查詢國家與商品代碼,並取得國際貨品與服務貿易資料。

可以做什麼
  • 將國家與地區名稱解析為 Comtrade M49 數字代碼,並提供可作為報告國的有效性與有效期間
  • 依關鍵字或代碼前綴搜尋 HS、SITC 商品代碼,列出 EBOPS 服務貿易類別
  • 取得雙邊貿易流資料(金額、數量、重量)以及年度服務貿易資料
  • 計算貿易差額,並依金額排序主要貿易夥伴或主要商品
  • 查詢哪些報告國、期間與分類組合已發布資料
  • 讀取國家清單與 HS 階層資源,以及一份工作流程指南技能
適用情境
適合需要回答國際貿易問題的情境,例如某國的進出口金額、貿易差額、主要貿易夥伴或主要貿易商品,以及服務貿易,並需要正確的 Comtrade 代碼來發起查詢。
執行需求
可作為公開託管的 Streamable HTTP 端點使用,也可透過 npx、bunx 或 Docker 在本機執行(需 Bun 1.4.0 以上或 Node.js 24 以上)。COMTRADE_SUBSCRIPTION_KEY 為選用,未設定時使用公開預覽端點,每次上游回應最多 500 筆記錄。查詢類工具不需金鑰。需要能連線至 Comtrade API 的網路。
安裝前請注意
未設定 COMTRADE_SUBSCRIPTION_KEY 時,每次上游請求最多回傳 500 筆記錄,單次呼叫可服務的期間數也有限,排名與差額結果可能不完整,應檢查截斷與未服務輸入欄位。公開託管實例以無金鑰方式執行於公開預覽端點。選用設定如 LOG_TOOL_FAILURE_PAYLOADS 會記錄失敗的工具參數與結果,且自由文字中的密鑰不會被遮蔽。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Un Comtrade Mcp Server,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Web executable,透過 Streamable HTTP。 遠端服務在工作區中設定後即可從網頁執行環境執行。

交給代理程式安裝

把這段提示詞貼上到 Claude Code、Codex、Cursor 等代理程式,或 SourceWeft 對話中。代理程式會讀取該伺服器的安裝指南,先向你展示發布者、端點和登入方式,經你同意後再把它新增到你的客戶端。金鑰不會寫進任何命令。

閱讀 https://sourceweft.com/mcp/io.github.cyanheads%2Fun-comtrade-mcp-server/install.md,並按其中說明把這個 MCP 伺服器接入我的客戶端。修改任何設定之前,先告訴我它的發布者、端點和登入方式,等我確認。不要把 API 金鑰寫進命令或我會提交的檔案;問我金鑰應從哪裡取得。

檢視代理程式所依據的安裝指南

其他 MCP 客戶端

把它新增到你客戶端的 mcpServers 設定中。

{
  "mcpServers": {
    "un-comtrade": {
      "type": "http",
      "url": "https://un-comtrade.caseyjhand.com/mcp"
    }
  }
}

README

@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 • 3 Resources


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

ToolDescription
comtrade_lookup_countriesResolve country and area names to Comtrade M49 numeric codes.
comtrade_search_commoditiesFind HS or SITC commodity codes in a selected edition by keyword, description, or code prefix.
comtrade_list_service_categoriesFind service trade categories in Comtrade's combined EB catalog, tagged with their EBOPS schemes, by keyword or parent code.
comtrade_get_trade_flowsFetch bilateral trade flow records — value, quantity, and weight per period/commodity/partner.
comtrade_get_trade_balanceCompute a country's trade balance (exports minus imports) across one or more periods.
comtrade_get_top_partnersRank trading partners by trade value for a reporter, commodity, and flow direction.
comtrade_get_top_commoditiesRank commodity categories by trade value for a reporter and flow direction.
comtrade_get_data_availabilityCheck which reporter/period/classification combinations have published data.
comtrade_get_services_tradeFetch international trade-in-services data — EB as reported (EB10, EB10S, or EB02 codes), or UN Comtrade's converted EB10/EB02 series.

Resources

ResourceDescription
comtrade://countriesComplete 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.
skill://un-comtrade-guide/SKILL.mdWorkflow guide for historical classifications, coverage, bilateral/mirror analysis, and unit values.

Country and HS reference data are also reachable through comtrade_lookup_countries and comtrade_search_commodities. The workflow guide ships with npm, Docker, MCPB, and plugins, and is available over MCP as a skill resource.

Capability reference

comtrade_lookup_countries tool

  • Accepts a partial or full country name, or an ISO alpha-2/alpha-3 code; role filters to "reporter", "partner" (only entries in UN's partner-area list), or "any" (default)
  • validAsReporter flag on each match — most regional groupings (e.g. World) are partner-only, but some report (e.g. the European Union, 97)
  • include_groups (default true) toggles regional/economic groupings in the results
  • Each match also pulls in entries sharing its ISO-3 identity, ordered exact ISO match, reporter-valid, current before expired, name, then code; reporter and partner-only area codes remain distinct
  • entryEffectiveDate and entryExpiredDate (YYYY-MM-DD) give each entity's validity, so historical entities (e.g. Fed. Rep. of Germany, ...1990) sort after current ones
  • Country references load from UN static files at startup — no subscription key required. Rows that fail validation are dropped and logged; startup fails on an empty catalog or when fewer than half a file's rows are valid

comtrade_search_commodities tool

  • Free-text keyword, partial description, or code-prefix search; classification (case-insensitive, default HS) selects the current HS reference, an HS edition H0–H6, or SITC SS/S1–S4
  • aggr_level uses the selected catalog's native levels: HS chapters/headings/subheadings use 2/4/6; SITC has levels 1–5. Omit for all levels. The HS all-commodities TOTAL is level 0, which no aggr_level filter returns
  • limit (default 50) is the page size; totalMatches, shown, and truncated describe the page, and offset with the returned nextOffset continues it
  • recommendedQueryCode on each result — the code to pass as cmd_code in trade queries, with the same classification

comtrade_list_service_categories tool

  • Lists the combined EB service categories, optionally filtered by keyword or parent_code; numeric and alphabetic codes are distinct entries. parent_code: "200" lists the EB10 and EB02 top levels
  • schemes on each category names the EBOPS scheme catalogs that list its code (EB10, EB10S, EB02); it is empty when none does and absent, with a notice, when the scheme catalogs could not be loaded. ebParent carries the parent the combined EB catalog gives a code when it differs from parent (TOTAL for EB10's top-level codes, whose parent is 200)
  • limit (default 100) is the page size; totalMatches, shown, and truncated describe the page, and offset with the returned nextOffset continues it
  • Returned id is the service_code for comtrade_get_services_trade

comtrade_get_trade_flows tool

  • Accepts a scalar reporter_code or an array; omission requires an explicit partner_code. Reporter arrays serve the first 20 distinct codes and disclose the remainder in unservedReporters. Served codes of an array that return no rows are listed in reportersWithoutRecords (referenceStatus, optional suggestedReporterCode; omitted when the response is truncated). A scalar partner-only code with no rows gets a notice naming its reporter-valid counterpart (250 → 251)
  • Requires flow_code (M import / X export / RX re-export / RM re-import) and period values, all YYYY or all YYYYMM. freq is optional: it is inferred from the period length, mixed lengths are rejected, and an explicit value must match. Up to 120 periods are accepted; keyless calls serve the first 8 (12 with a subscription key). Periods past the cap, or whose request is rate limited or runs out of time, are listed in unservedPeriods with a notice; if every period fails the call returns rate_limited or deadline_exceeded
  • partner_code: 0 returns the World total; omit it for a per-partner breakdown. classification (case-insensitive, default HS) supports HS, H0–H6, and SITC S1–S4/SS. Explicit HS editions require authenticated data access; keyless HS returns as-reported editions, identified by each row's classificationCode
  • cmd_code[] accepts up to 200 codes and serves the first 20, listing the rest in unservedCmdCodes; omit it or pass ["TOTAL"] for cross-commodity totals. truncated: true plus truncationHint means the response hit the 500-record cap; isReported separates directly reported rows from UN-estimated ones
  • Quantity and alternate quantity retain unit codes/abbreviations and estimation flags where available. UN Comtrade sends 0 for what it does not report, so qty/altQty of 0 with unit code -1, and netWgt/grossWgt/cifvalue/fobvalue of 0 beside a positive primaryValue, are omitted: an absent field means not reported, not zero. A 0 in a real unit stays a measurement

comtrade_get_trade_balance tool

  • Returns balanceUsd (signed), exportsUsd, importsUsd, and coverageRatio (exports / imports) per period. Optional cmd_code[] restricts the balance to HS or SITC commodities
  • partner_code defaults to World (0); a country code computes the reporter's bilateral balance and is echoed with the partner name. classification is case-insensitive with default HS; freq is optional and inferred from the period length (mixed lengths are rejected; an explicit value must match)
  • Accepts up to 120 periods and 200 codes. Keyless calls serve the first 4 periods (two requests each; 12 with a subscription key) and 20 codes, listing the rest in unservedPeriods/unservedCmdCodes; a period is served only when both flows complete, and one whose export or import request is rate limited or runs out of time is listed too. A notice warns when either flow hit the 500-record cap and the balance may be incomplete
  • A partner-only reporter code (0 World, 250 Metropolitan France) with no data fails with partner_only_reporter, naming the reporter-valid counterpart when one exists (250 → 251)
  • mirrorCaveat on 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 single period; optional single cmd_code (omit for total merchandise trade) in the selected classification (case-insensitive, default HS; H0–H6 with a subscription key, SITC S1–S4/SS)
  • Infers annual or monthly frequency from the period; monthly values require a calendar month from 01 through 12
  • Returns the top limit partners (default 10; any larger value is honored, with no return-all threshold), each with rank, primaryValueUsd, and sharePercent; totalPartners and totalValueUsd cover every partner retrieved, and shares divide by totalValueUsd; classification names the catalog the cmd_code was read in
  • truncated: true when the fetch hit the 500-record cap. An empty result for a partner-only reporter code ends its notice with the reporter-valid counterpart (250 → 251)

comtrade_get_top_commodities tool

  • Takes one reporter_code, flow_code, and single period; aggr_level is 2 (HS chapter, default) or 4 (heading). partner_code defaults to World (0); set it to scope to one partner
  • Infers frequency from period. Fetches matching TOTAL to identify the reporter's HS edition, then queries that edition's category codes in paced chunks, splitting capped chunks
  • Returns the top limit categories (default 10; any larger value is honored, with no return-all threshold). Complete coverage permits ranks; shares use denominatorValueUsd from TOTAL, while totalValueUsd and totalCommodities cover every category retrieved
  • coverageComplete, coverageNotice, and missingCodes describe retrieval; codes not reached within the call's time budget are listed in missingCodes. Incomplete results retain available categories without ranks or shares; truncated remains true. A TOTAL with no rows ends the ranking with an empty result and truncated: false; for a partner-only reporter code its notice names the reporter-valid counterpart. Ranking can require several upstream requests

comtrade_get_data_availability tool

  • All filters optional — reporter_code, period, freq (A/M; inferred from period, A when period is omitted, and an explicit value must match it), type_code (C goods / S services, default C), classification (omitted or blank resolves to HS for goods, EB10 for services; upstream identifiers such as B4 and B5 are also accepted)
  • Returns per-dataset totalRecords, firstReleased, and lastReleased where available; omit all filters to browse goods availability
  • limit defaults to 50 and offset to 0. Results are sorted before slicing; totalDatasets, shown, and nextOffset support stable page traversal. truncated identifies a partial page. Paging still fetches the matching upstream availability list
  • An empty result for a partner-only reporter code ends its notice with the reporter-valid counterpart (250 → 251)
  • Annual data typically publishes 3–12 months after the reference year — call this before querying recent periods

comtrade_get_services_trade tool

  • Takes one reporter_code, flow_code (M imports/debits, X exports/credits), annual period values (YYYY), and optional partner_code (0 for all partners combined). Up to 120 periods are accepted; keyless calls serve the first 8 (12 with a subscription key). Periods past the cap, or whose request is rate limited or runs out of time, are listed in unservedPeriods with a notice
  • classification (case-insensitive, default EB; blank means EB) selects EB as reported, with each reporter-period in its own scheme (EB10, EB10S, or EB02 codes), or UN Comtrade's converted EB10/EB02 series. EB10S has no converted series and is rejected; its rows are served only under EB. Each row's classificationCode identifies its classification and isOriginalClassification says whether it is as reported or converted
  • service_code filters to one category from comtrade_list_service_categories (3 is transport; SA is manufacturing services), which lists each code's schemes. Omit it to get every reported category at mixed levels, with totals (200 for EB10 and EB02, S for EB10S) beside their components: don't sum the rows
  • An empty result's notice names the code's scheme, routes to comtrade_get_data_availability with classification: "EB", and suggests the converted series when one applies; for a partner-only reporter it names the reporter-valid counterpart
  • truncated: true plus truncationHint when 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, isGroup, and entryEffectiveDate/entryExpiredDate (YYYY-MM-DD) where upstream lists them
  • Loaded from the same startup reference cache comtrade_lookup_countries searches

comtrade://hs-classification/{level} resource

  • level path param accepts 2 (chapters), 4 (headings), or 6 (subheadings); any other value throws a validation error
  • Returns each code's description, parent, and isLeaf; full leaf enumeration is too large to inject — use comtrade_search_commodities for 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:

  • Country codes, current HS hierarchy, and EB categories load from UN static files at startup; historical HS/SITC editions, quantity units, and the EB10.json/EB10S.json/EB02.json scheme catalogs (category scheme tags and the services empty-result notice) load lazily and cache successful responses. Invalid rows in a reference file are dropped and logged; startup fails on an empty catalog or when fewer than half a file's rows are valid
  • 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_balance runs export and import fetches concurrently)
  • Retry with exponential backoff on transient failures, honoring an upstream Retry-After header when present
  • Description enrichment uses the row's classification edition and preserves upstream labels. Optional reference failures retain trade values and codes with a notice

Agent-friendly output:

  • truncated: true plus a recovery hint when a public preview response reaches 500 records
  • isReported flag on trade flow records distinguishes directly-reported values from UN-estimated/aggregated rows
  • validAsReporter on country lookups prevents constructing invalid queries with partner-only area codes
  • mirrorCaveat on 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 that start at least 4 seconds apart. Each call serves 8 periods for flows and services and 4 for balance (two requests per period); periods past that, or that fail, come back in unservedPeriods. Point any MCP client at it via Streamable HTTP:

json
{  "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.

json
{  "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):

json
{  "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:

json
{  "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:

sh
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.4.
  • 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

  1. Clone the repository:
sh
git clone https://github.com/cyanheads/un-comtrade-mcp-server.git
  1. Navigate into the directory:
sh
cd un-comtrade-mcp-server
  1. Install dependencies:
sh
bun install
  1. Configure environment:
sh
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.

VariableDescriptionDefault
COMTRADE_SUBSCRIPTION_KEYAzure API Management subscription key from comtradedeveloper.un.org. Without it, tools use the public preview endpoint (500-record cap).—
COMTRADE_API_BASE_URLOverride the Comtrade API base URL.https://comtradeapi.un.org
MCP_TRANSPORT_TYPETransport: stdio or http.stdio
MCP_HTTP_PORTHTTP server port.3010
MCP_HTTP_ENDPOINT_PATHHTTP endpoint path./mcp
MCP_PUBLIC_URLPublic origin override for reverse-proxy deployments.—
MCP_SESSION_MODEHTTP session mode: auto, stateful, or stateless.stateless
MCP_AUTH_MODEAuth mode: none, jwt, or oauth.none
MCP_LOG_LEVELLog level (debug, info, warning, error).info
LOGS_DIRDirectory for log files (Node.js only).<project-root>/logs
LOG_TOOL_FAILURE_PAYLOADSLog 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_TYPEStorage backend: in-memory, filesystem, supabase, cloudflare-kv/r2/d1.in-memory
OTEL_ENABLEDEnable OpenTelemetry instrumentation.false
OTEL_EXPORTER_OTLP_ENDPOINTOTLP base URL for traces (/v1/traces) and metrics (/v1/metrics).—
OTEL_EXPORTER_OTLP_LOGS_ENDPOINTOpt-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:

    sh
    # One-time buildbun run rebuild
    # Run the built serverbun run start:stdio# orbun run start:http
  • Run checks and tests:

    sh
    bun run devcheck   # Lint, format, typecheck, securitybun run test       # Vitest test suitebun run lint:mcp   # Validate MCP definitions against spec

Docker

sh
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

DirectoryPurpose
src/index.tscreateApp() entry point — registers tools, resources, and inits services.
src/configEnvironment variable parsing and validation with Zod.
src/mcp-server/toolsTool definitions (*.tool.ts). Nine tools across reference resolution, trade data, and workflow aggregations.
src/mcp-server/resourcesResource definitions (*.resource.ts). Country list and HS hierarchy resources.
src/services/comtrade-dataComtradeDataService — authenticated/preview request builder with retry and key fallback.
src/services/comtrade-referenceComtradeReferenceService — reference data loader (countries, HS, EBOPS), startup cache, keyword search.
src/services/comtrade-metaComtradeMetaService — data availability requests and validation.
skills/Published workflow guide for agents calling the server.
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/catch in tool logic
  • Use ctx.log for request-scoped logging, ctx.state for tenant-scoped storage
  • Register new tools and resources in src/index.ts
  • Wrap external API calls: validate raw → normalize to domain type → return output schema; never fabricate missing fields
  • Use the matching classification's reference cache for commodity descriptions; lazy reference failures must preserve useful trade records and propagate caller cancellation

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:

sh
bun run devcheckbun run test

License

Apache-2.0 — see LICENSE for details.

來源:README.md,提交 7bd10aa

工具

9

comtrade_lookup_countries

Lookup Countries / Areas

Resolve country and area names to Comtrade M49 numeric codes used in all data queries. Accepts a partial name, full name, or ISO alpha-2/alpha-3 code (e.g. "United States", "USA", "US"). Returns matching entries with their numeric code, ISO identifiers, a validAsReporter flag, and validity dates; historical entities such as Fed. Rep. of Germany (...1990) are listed after current ones. World (code 0) is a valid partner but not a valid reporter, while some groupings, such as the European Union (97), do report — check validAsReporter. Use this before any trade data tool that requires reporter_code or partner_code. To aggregate across all partners, use partner code 0 (World) — no lookup needed.

輸入參數rolequery必填include_groups

comtrade_search_commodities

Search Commodity Codes

Find HS or SITC commodity codes by keyword, partial description, or code prefix in the selected classification. Returns descriptions, native aggregation levels, parents, leaf status, and recommendedQueryCode for subsequent trade queries. HS uses levels 2 (chapter), 4 (heading), and 6 (subheading); SITC uses levels 1–5. Select the edition matching the trade records when interpreting historical codes. Each page holds up to limit matches; continue with nextOffset using the same query, classification, and aggr_level.

輸入參數limitquery必填offsetaggr_levelclassification

comtrade_list_service_categories

List Service Trade Categories (EB)

List service trade categories from the combined EB catalog, including numeric EBOPS and SDMX codes. Returns category codes, descriptions, parent codes, and the EBOPS scheme catalogs that list each code: EB10 (EBOPS 2010), EB10S (EBOPS 2010 SDMX codes), EB02 (EBOPS 2002). Filter by keyword (e.g. "transport", "financial", "travel") or browse direct children of a parent code; "200" lists the EB10 and EB02 top levels. Use the returned id as service_code in comtrade_get_services_trade. Code 3 is transport; SA is manufacturing services. Each page holds up to limit categories; continue with nextOffset using the same query and parent_code.

輸入參數limitqueryoffsetparent_code

comtrade_get_trade_flows

Get Trade Flow Records

Fetch bilateral trade flow records — the primary data retrieval tool. Returns trade value in USD (primaryValue — FOB for exports, CIF for imports), quantity, net weight, and period/commodity/partner metadata for each row. Accepts multiple periods and commodity codes per call; pass partner_code 0 to get totals aggregated across all partners. Omit cmd_code or pass "TOTAL" to aggregate all commodities. Keyless preview makes one request per served period, at least 4 seconds apart, with a 500-record cap per request. Use comtrade_lookup_countries to resolve reporter/partner codes and comtrade_search_commodities to resolve HS codes. For SITC, supply codes from the selected SITC revision.

輸入參數freqperiod必填cmd_codeflow_code必填partner_codereporter_codeclassification

comtrade_get_trade_balance

Get Trade Balance

Compute the trade balance for a country over one or more periods — total exports minus total imports — with optional HS or SITC commodity filter. Keyless preview makes two requests per served period, at least 4 seconds apart; authenticated calls batch periods. Returns the signed balance (USD), export value, import value, and coverage ratio (exports / imports). Note: mirror asymmetry is common — balance reflects values as reported by this country; the same flow may be recorded differently by the partner. Uses comtrade_lookup_countries to resolve reporter codes.

輸入參數freqperiod必填cmd_codepartner_codereporter_code必填classification

comtrade_get_top_partners

Get Top Trading Partners

Rank trading partners for a reporter by trade value for a given commodity and flow direction. Returns the top N partners sorted by descending value — answers "who does country X mainly export product Y to?" or "where does country X mainly import product Z from?" for a single period. Fetches a disaggregated breakdown across all partners then sorts locally. Takes an HS or SITC code in the selected classification; omit cmd_code to rank partners for total trade.

輸入參數limitperiod必填cmd_codeflow_code必填reporter_code必填classification

comtrade_get_top_commodities

Get Top Trade Commodities

Rank HS chapters (2-digit) or headings (4-digit) by trade value for one reporter, flow, and annual or monthly period. Retrieves matching TOTAL and the reporter’s HS edition, then queries explicit commodity codes in chunks; capped chunks are subdivided. Shares use matching TOTAL. Incomplete coverage returns available categories without ranks or shares and identifies unresolved codes. Defaults to World; optionally select one bilateral partner. Counterpart to comtrade_get_top_partners.

輸入參數limitperiod必填flow_code必填aggr_levelpartner_codereporter_code必填

comtrade_get_data_availability

Check Data Availability

Check which reporter/period/classification combinations have published data before constructing expensive trade queries. Returns dataset records with period, classification, record count, and first/latest release dates. Call this before querying recent periods — annual data is typically published 3–12 months after the reference year and not all countries report every year. Omit filters to browse the availability index, 50 rows by default. Continue with nextOffset using the same filters and limit.

輸入參數freqlimitoffsetperiodtype_codereporter_codeclassification

comtrade_get_services_trade

Get Services Trade Data

Fetch annual international trade-in-services data. Classification EB (default) serves each reporter-period as reported, in its own scheme (EB10, EB10S or EB02 codes); EB10 or EB02 selects UN Comtrade's conversion of other schemes into that one. Each row names its classification and whether it is original or converted. Same bilateral structure as goods trade: returns flow value in USD, period, and reporter/partner/category metadata for each row. Use comtrade_list_service_categories to find a service code and its scheme before querying. Keyless preview makes one request per served period, at least 4 seconds apart, capped at 500 records per request. Services coverage is more limited than goods trade.

輸入參數period必填flow_code必填partner_codeservice_codereporter_code必填classification

版本歷史

6
  1. v0.3.1最新Nov 5, 2026
  2. v0.3.0Nov 3, 2026
  3. v0.2.0Oct 13, 2026
  4. v0.1.8Oct 7, 2026
  5. v0.1.7Sep 21, 2026
  6. v0.1.6Sep 16, 2026

評分

已滿足適用檢查項的 100%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通必需25 分
  • 已宣告認證方式必需10 分
  • 已列出工具必需15 分
  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分