Skip to main content
Glama
census-trade-mcp-server

census-trade-mcp-server

by jslagle9

uscensus-intl-trade-api-mcp

An MCP (Model Context Protocol) server for the U.S. Census Bureau's International Trade Data API — monthly U.S. export and import statistics, January 2010–present, by Harmonized System (HS), NAICS, End-Use, SITC, USDA (Ag/Non-Ag), and Advanced Technology classifications, plus state- and port-level detail.

Setup

  1. Get a free Census API key: https://api.census.gov/data/key_signup.html (you'll get an email with an activation link — click it before using the key).

  2. Install dependencies and build:

    npm install
    npm run build
  3. Set your API key:

    cp .env.example .env
    # edit .env and set CENSUS_API_KEY
  4. Add to your MCP client (e.g. Claude Desktop / Claude Code config):

    {
      "mcpServers": {
        "census-trade": {
          "command": "node",
          "args": ["/absolute/path/to/uscensus-intl-trade-api-mcp/dist/index.js"],
          "env": { "CENSUS_API_KEY": "your_40_character_key_here" }
        }
      }
    }

By default the server runs over stdio. Set TRANSPORT=http (and optionally PORT) to run it as a local streamable-HTTP server instead (binds to 127.0.0.1 only).

Related MCP server: Census MCP Server

Tools

Tool

Purpose

census_trade_list_datasets

Describes the 9 available datasets (hs, naics, enduse, sitc, usda, hitech, statehs, statenaics, porths) and what geography/detail each supports.

census_trade_get_dataset_variables

Fetches the valid field names for a given dataset + direction straight from Census's own metadata, to avoid "unknown variable" errors.

census_trade_query_exports

General-purpose query tool for U.S. export data — any dataset, country/commodity/district/state/port filters, time range.

census_trade_query_imports

Same, for U.S. import data.

census_trade_get_trade_balance

Workflow tool: computes exports − imports for one or more countries/groupings over a period in a single call.

census_trade_get_top_partners

Workflow tool: ranks countries by export/import value for a period — the Census API itself doesn't sort results, so this does it for you.

census_trade_lookup_country_code

Looks up the numeric CTY_CODE (Schedule C) needed to filter by country, region, or trade bloc (e.g. NAFTA, EU, OPEC). Works offline, no API key needed.

Testing

  • node scripts/smoke-test.mjs — starts the server, lists tools, and exercises the two tools that don't require a live Census API call. No real API key needed.

  • CENSUS_API_KEY=<real key> node scripts/live-test.mjs — exercises real Census API calls end-to-end (needs a real key and outbound network access to api.census.gov).

Evaluations

evaluation/questions.xml has 10 verified Q&A pairs for testing how well an LLM can use this server, built on the mcp-builder evaluation harness (evaluation/evaluation.py). All questions use January/June 2013 data — final, long-settled figures chosen so the answers never change.

pip install -r evaluation/requirements.txt
export ANTHROPIC_API_KEY=your_api_key
python evaluation/evaluation.py \
  -t stdio -c node -a dist/index.js \
  -e CENSUS_API_KEY=<your census key> \
  -o evaluation/report.md \
  evaluation/questions.xml

Notes on the underlying API

  • Filtering by country uses a numeric CTY_CODE (Schedule C), not the country name — use census_trade_lookup_country_code to translate.

  • Descriptive text fields (CTY_NAME, DIST_NAME, *_LDESC, etc.) require their matching code field also be requested, or the API errors.

  • Don't mix commodity-classification parameters across datasets (e.g. don't filter by NAICS on the hs dataset).

  • Large, unfiltered queries (e.g. all countries × all 10-digit HS codes) commonly time out — narrow with filters or split wildcard queries (E_COMMODITY=1*, then 2*, etc.) and combine client-side.

  • A response with zero rows isn't necessarily an error — it can just mean no trade occurred for that filter combination.

  • Quantity fields (QTY_1_MO, QTY_2_MO, GEN_QY1_MO, GEN_QY2_MO, CON_QY1_MO, CON_QY2_MO, and their *_YR variants) report "0" for both true zeros and missing/unavailable data — always request the matching *_FLAG field (e.g. QTY_1_MO_FLAG) alongside a quantity field; "M" means missing, blank means a true zero.

  • Requesting CTY_CODE without summary_level="DET" returns individual countries and regional/bloc groupings (e.g. 4XXX Europe, 0001 OPEC) mixed in the same response — summing across all rows double-counts. Set summary_level="DET" before aggregating across countries yourself.

Full reference: Census International Trade Data API User Guide (PDF).

Available Tools

7 tools
census_trade_get_dataset_variablesGet Valid Variables for a Trade DatasetA
Read-onlyIdempotent

List every valid Census API variable (field) name for a specific dataset + trade direction, straight from the Census API's own metadata.

Use this before calling census_trade_query_exports/imports when you're unsure which variable names are valid to put in the "get" or "filters" parameters - the Census API rejects unknown variable names with a 400 error, and valid variables differ by dataset (e.g. "SITC" is only valid on the sitc dataset, not hs).

Args:

  • direction ('exports' | 'imports'): which trade direction's variable list to fetch

  • dataset (string): dataset code, e.g. 'hs', 'naics', 'statehs' (see census_trade_list_datasets for the full list)

  • response_format ('markdown' | 'json'): output format (default 'markdown')

Returns: For each variable - its name, human-readable label, whether it's required, and its type (string/int/datetime).

Examples:

  • Use when: "What fields can I request from the imports NAICS endpoint?"

  • Use when: You got a "unknown variable" error from census_trade_query_exports and need to find the correct name

  • Don't use when: You just want dataset descriptions, not field-level detail - use census_trade_list_datasets instead

Inputs: dataset (required), direction (required), response_format.

census_trade_get_top_partnersRank Top Trading PartnersA
Read-onlyIdempotent

Return the top N countries ranked by U.S. export or import value for a given period and (optionally) a specific commodity - the Census API itself does not sort results, so this tool fetches the full country breakdown and sorts it for you.

Args:

  • direction ('exports' | 'imports'): rank by export destinations or import sources

  • dataset (string, default 'hs'): which classification dataset to pull from (see census_trade_list_datasets)

  • time (string, optional) or year+months (optional): time period

  • value_field (string, optional): value field to rank by, e.g. 'ALL_VAL_YR' for year-to-date exports. Defaults to ALL_VAL_MO (exports) or GEN_VAL_MO (imports).

  • filters (object, optional): extra filters, e.g. {"E_COMMODITY":"2709*"} to rank partners for crude oil exports only

  • top_n (number, default 10, max 50): how many partners to return

  • response_format ('markdown' | 'json', default 'markdown')

Returns: Ranked list with country, value in USD, and percentage share of total trade across all countries in the response, plus the grand total and count of countries with any trade.

Examples:

  • Use when: "Who are our top 5 export markets in 2024?" -> direction="exports", top_n=5, year="2024", months=[...]

  • Use when: "Which countries do we import the most crude oil from?" -> direction="imports", filters={"I_COMMODITY":"2709*"}, time="2024-06"

  • Don't use when: You want a two-way trade balance calculation - use census_trade_get_trade_balance instead.

Inputs: direction (required), time, year, top_n, +5 more.

census_trade_get_trade_balanceCompute U.S. Trade Balance With CountriesA
Read-onlyIdempotent

Compute the U.S. trade balance (exports minus imports) with one or more countries or country groupings, for a given time period, in one call.

This is a workflow tool that combines an exports/hs query and an imports/hs query (which census_trade_query_exports/imports would otherwise require two separate calls to do), sums values across the requested period, and computes the balance per country plus a combined total.

Args:

  • countries (string[]): one or more CTY_CODE values, e.g. ["1220","2010"] for Canada and Mexico (use census_trade_lookup_country_code to find codes)

  • time (string, optional) or year+months (optional): time period, e.g. time="2024" is invalid - use time="from 2024-01 to 2024-12" or year="2024", months=["01",...,"12"]

  • hs_code (string, optional): restrict to a specific HS commodity code/prefix instead of total trade, e.g. "87" for vehicles

  • import_basis ('general' | 'consumption', default 'general'): which import total to use

  • response_format ('markdown' | 'json', default 'markdown')

Returns: Per-country exports, imports, and balance in USD, plus a combined total row. Positive balance = U.S. trade surplus with that country; negative = deficit.

Examples:

  • Use when: "What's the U.S. trade balance with China in 2024?" -> countries=["5700"], year="2024", months=["01",...,"12"]

  • Use when: "Compare our vehicle trade balance with Japan, Germany, and South Korea last year" -> countries=["5880","4280","5800"], hs_code="87", year="2023", months=[...]

  • Don't use when: You just need one direction's raw data - use census_trade_query_exports or census_trade_query_imports.

Inputs: countries (required), time, year, months, +3 more.

census_trade_list_datasetsList Census International Trade DatasetsA
Read-onlyIdempotent

List the 9 commodity classification / geography datasets available in the Census International Trade Data API, for both exports and imports.

Use this first when you're not sure which dataset to query. Each dataset covers the same underlying monthly trade data (2010-present) but organizes it by a different commodity classification (HS, NAICS, End-Use, SITC, USDA, Advanced Technology) or geography (state, port instead of customs district).

Args: none.

Returns: For each dataset - its short code (used as the "dataset" parameter in census_trade_query_exports/imports), full name, description, level of detail available for exports vs. imports, and which commodity-code parameters it accepts.

Examples:

  • Use when: "What trade datasets are available?" or "Which dataset has state-level export data?"

  • Don't use when: You already know the dataset code you need - go straight to census_trade_query_exports/imports.

Inputs: no named parameters.

census_trade_lookup_country_codeLook Up Census Trade CTY_CODEA
Read-onlyIdempotent

Look up the Census Bureau Schedule C CTY_CODE (and country groupings like OPEC, NAFTA, European Union, or world regions) needed to filter census_trade_query_exports/imports by country.

The Census API filters trade data by a numeric CTY_CODE, not by country name (CTY_NAME can only be requested as a descriptive field alongside CTY_CODE, not used as a filter by itself). Use this tool to translate a country name into the code you need.

Args:

  • query (string): country/region/bloc name or partial name, e.g. "korea", "vietnam", "european union"

  • limit (number, default 10): max matches to return

  • response_format ('markdown' | 'json', default 'markdown')

Returns: Matching entries with their CTY_CODE, name, and ISO alpha-2 code (for individual countries) or just code+name (for groupings). Note South Korea is listed as "South Korea (Republic of Korea)" and North Korea as "North Korea (Democratic People's Republic of Korea)".

Examples:

  • Use when: "What's the country code for Vietnam?" -> query="vietnam" -> returns CTY_CODE 5520

  • Use when: "I want export data for all EU countries as a group" -> query="european union" -> returns CTY_CODE 0003, then pass that as CTY_CODE in census_trade_query_exports filters

  • Don't use when: You already have the CTY_CODE - go straight to census_trade_query_exports/imports.

Inputs: query (required), limit, response_format.

census_trade_query_exportsQuery U.S. Export Trade DataA
Read-onlyIdempotent

Query monthly U.S. export statistics (January 2010-present) from the Census International Trade Data API.

This is the general-purpose tool for pulling export data by commodity (HS/NAICS/End-Use/SITC/USDA/Hi-Tech), country, customs district, state, or port, for any combination of value/quantity/weight measures.

Args:

  • dataset (string): which classification/geography dataset, e.g. 'hs' for Harmonized System (see census_trade_list_datasets)

  • get (string[]): variable names to return as columns, e.g. ["CTY_CODE","CTY_NAME","ALL_VAL_MO"]

  • time (string, optional): 'YYYY-MM' or 'from YYYY-MM to YYYY-MM'

  • year (string, optional) + months (string[], optional): alternative to 'time', e.g. year="2024", months=["01","02","03"]

  • filters (object, optional): e.g. {"CTY_CODE":"1220"} for Canada, {"E_COMMODITY":"0805*"} for HS codes starting with 0805 (citrus fruit)

  • comm_level (string, optional): e.g. "HS2" to get 2-digit HS totals instead of full detail

  • summary_level (string, optional): "DET" for individual countries only, "CGP" for country groupings only

  • limit (number, default 100): max rows returned

  • response_format ('markdown' | 'json', default 'markdown')

Best practices (per the Census API User Guide):

  • Prefer narrow queries: the Census API times out on very large requests (e.g. all countries x all HS10 codes). Add country/commodity/district filters, or split wildcard commodity queries (e.g. query "1*" then "2*" separately) and combine results yourself.

  • Descriptive text fields (CTY_NAME, DIST_NAME, E_COMMODITY_LDESC/I_COMMODITY_LDESC, NAICS_LDESC, SITC_LDESC, etc.) require their matching code field (CTY_CODE, DISTRICT, E_COMMODITY/I_COMMODITY, NAICS, SITC) to also be in "get", or the API errors.

  • Only use commodity-classification parameters that match the chosen dataset (e.g. don't filter by NAICS on the "hs" dataset) - use census_trade_get_dataset_variables to check.

  • Results are NOT sorted by value; if you need a ranked list (e.g. top trading partners), use census_trade_get_top_partners instead, or sort the returned rows yourself.

  • A request that returns zero rows is not necessarily an error - it may just mean there was no trade for that combination of filters and time period.

Returns: Rows as either a markdown table or JSON, each row containing the fields requested in "get" plus "time".

Examples:

  • Use when: "What did the U.S. export to Germany in HS code 8703 (cars) in 2024?" -> dataset="hs", get=["E_COMMODITY","E_COMMODITY_LDESC","ALL_VAL_MO"], time="2024-01", filters={"CTY_CODE":"4280","E_COMMODITY":"8703*"}

  • Use when: "Show monthly export value trend for all countries, Jan-Jun 2023" -> get=["ALL_VAL_MO"], time="from 2023-01 to 2023-06"

  • Don't use when: You need import data - use census_trade_query_imports.

  • Don't use when: You want a country trade balance or a sorted list of top partners - use census_trade_get_trade_balance or census_trade_get_top_partners.

Inputs: get (required), dataset (required), time, year, +6 more.

census_trade_query_importsQuery U.S. Import Trade DataA
Read-onlyIdempotent

Query monthly U.S. import statistics (January 2010-present) from the Census International Trade Data API.

This is the general-purpose tool for pulling import data by commodity (HS/NAICS/End-Use/SITC/USDA/Hi-Tech), country, customs district, state, or port, for any combination of value/quantity/weight measures. Import value fields typically start with GEN_ (general imports) or CON_ (imports for consumption) rather than ALL_ (which is export-only).

Args:

  • dataset (string): which classification/geography dataset, e.g. 'hs' for Harmonized System (see census_trade_list_datasets)

  • get (string[]): variable names to return as columns, e.g. ["CTY_CODE","CTY_NAME","GEN_VAL_MO"]

  • time (string, optional): 'YYYY-MM' or 'from YYYY-MM to YYYY-MM'

  • year (string, optional) + months (string[], optional): alternative to 'time'

  • filters (object, optional): e.g. {"CTY_CODE":"5700"} for China, {"I_COMMODITY":"8471*"} for HS codes starting with 8471 (computers)

  • comm_level (string, optional): e.g. "HS2" to get 2-digit HS totals instead of full detail

  • summary_level (string, optional): "DET" for individual countries only, "CGP" for country groupings only

  • limit (number, default 100): max rows returned

  • response_format ('markdown' | 'json', default 'markdown')

Best practices (per the Census API User Guide):

  • Prefer narrow queries: the Census API times out on very large requests (e.g. all countries x all HS10 codes). Add country/commodity/district filters, or split wildcard commodity queries (e.g. query "1*" then "2*" separately) and combine results yourself.

  • Descriptive text fields (CTY_NAME, DIST_NAME, E_COMMODITY_LDESC/I_COMMODITY_LDESC, NAICS_LDESC, SITC_LDESC, etc.) require their matching code field (CTY_CODE, DISTRICT, E_COMMODITY/I_COMMODITY, NAICS, SITC) to also be in "get", or the API errors.

  • Only use commodity-classification parameters that match the chosen dataset (e.g. don't filter by NAICS on the "hs" dataset) - use census_trade_get_dataset_variables to check.

  • Results are NOT sorted by value; if you need a ranked list (e.g. top trading partners), use census_trade_get_top_partners instead, or sort the returned rows yourself.

  • A request that returns zero rows is not necessarily an error - it may just mean there was no trade for that combination of filters and time period.

Returns: Rows as either a markdown table or JSON, each row containing the fields requested in "get" plus "time".

Examples:

  • Use when: "What did the U.S. import from China in HS 8471 (computers) in March 2024?" -> dataset="hs", get=["I_COMMODITY","I_COMMODITY_LDESC","GEN_VAL_MO"], time="2024-03", filters={"CTY_CODE":"5700","I_COMMODITY":"8471*"}

  • Use when: "Total general imports by state, Q1 2023" -> dataset="statehs", get=["STATE","GEN_VAL_MO"], time="from 2023-01 to 2023-03"

  • Don't use when: You need export data - use census_trade_query_exports.

  • Don't use when: You want a country trade balance or a sorted list of top partners - use census_trade_get_trade_balance or census_trade_get_top_partners.

Inputs: get (required), dataset (required), time, year, +6 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.6/5.0

    Scored across 7 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose: querying exports vs. imports, listing datasets, inspecting variables, computing trade balance, ranking partners, and looking up country codes. There is no functional overlap that would cause an agent to select the wrong tool.

    Naming Consistency5/5

    All tool names follow the consistent verb_noun pattern with the census_trade_ prefix (query_exports, query_imports, list_datasets, get_dataset_variables, get_trade_balance, get_top_partners, lookup_country_code). This makes the API surface predictable and easy to navigate.

    Tool Count5/5

    Seven tools is a well-scoped size for this domain. Each tool serves a distinct and necessary function for working with Census trade data, without being bloated or too minimal.

    Completeness5/5

    The set covers the full workflow: dataset discovery, variable inspection, raw data queries for exports/imports, derived analytics (trade balance, top partners), and supporting lookups (country codes). There are no obvious dead ends or missing operations for the stated purpose of accessing U.S. Census trade statistics.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      D
      quality
      D
      maintenance
      Servidor MCP para a API do ComexStat, ferramenta de acesso às estatísticas de comércio exterior do Brasil.
      20
      9 npm
      2
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Provides access to UN Comtrade international bilateral trade data via an MCP server, enabling AI agents to query trade statistics through natural language.
      85 npm
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      MCP server to query U.S. Census Bureau data, variables, and geography through 7 tools supporting dataset discovery, variable search, geography resolution, and data queries with suppression code decoding.
      570 npm
      3
      Apache 2.0