Skip to main content
Glama
mcp-comex-brasil
by PHIAI-IO

mcp-comex-brasil

MCP server for Brazilian foreign-trade data — with the dataset's traps corrected in the response.

Four tools that don't lie, instead of forty that don't know.


The problem this server solves

An MCP server that merely exposes a dataset hands the agent a clean API to a wrong number. The plumbing doesn't know the field lies.

Comex Stat — the official Brazilian foreign-trade database, published by the Foreign Trade Secretariat / Federal Revenue Service — has a defect that no documentation warns about:

Filtering the transport-mode field by AÉREA returns 139.6 million kg of Chinese imports in 2026 (Jan–Jul). Cross-referencing these same records with the clearance point, only 34.0 million (24%) passed through an airport. The other 89.7 million cleared at seaports and are ammonium sulfate and phosphatic fertilizers — cargo that does not fly, at US$0.29/kg freight.

Uncorrected: air weight overstated 4.1× and freight per kg understated by 70%. The error is silent — nothing in the query flags it.

This server applies the correction, and returns the evidence for why it is needed.

Related MCP server: Receita Federal: Radar (Habilitação Comércio Exterior)

The two guarantees

  1. Every response carries the known defects that apply to that query, with measured evidence and verification provenance.

  2. The critical correction is applied to the result, not merely warned about. The air channel already means "air mode cleared at an airport". The contaminated block remains queryable as air_declared_at_port, deliberately — for anyone who wants to inspect it.

What the dataset has that published summaries discard

The import files carry VL_FRETE and VL_SEGURO — freight and insurance as declared to customs. It is the best systematic measure of realized cost available publicly, and almost nobody uses it.

China → Brazil, Jan–Jul 2026, already corrected:

Channel

Weight (kg)

Freight US$/kg

Freight % of FOB

Value density

Air (airport)

33,993,130

10.81

9.37%

US$115.36/kg

Sea

16,074,641,185

0.142

5.68%

US$2.51/kg

Air costs 76× more per kilogram and only 1.65× more per dollar of goods. This corridor's modal split is not a freight decision — it is a value-density decision.

Install

Requires Node ≥ 22.5 (uses the built-in SQLite — zero native dependencies, no node-gyp).

git clone <repo> && cd mcp-comex-brasil
npm install && npm run build
npm run db:build -- --years 2025,2026        # baixa da fonte oficial e monta o SQLite

db:build fetches the files straight from balanca.economia.gov.br. No data is redistributed by this package — the database is built on your machine, always fresh from the source.

Useful options:

npm run db:build -- --years 2026 --countries 160        # só China, base pequena e rápida
npm run db:build -- --years 2024,2025,2026 --flows import,export

Configuring the MCP client

{
  "mcpServers": {
    "comex": {
      "command": "node",
      "args": ["--experimental-sqlite", "/caminho/para/mcp-comex-brasil/dist/index.js"],
      "env": { "COMEX_LANG": "pt" }
    }
  }
}

COMEX_LANG accepts pt (default) or en. COMEX_DB overrides the database path.

The four tools

Tool

What it does

comex_trade_flow

Value, weight and value density by year, month, country, HS code and channel. The air channel is already corrected.

comex_freight_cost

Declared freight and insurance per channel: US$/kg and % of FOB. Imports only.

comex_data_caveats

The dataset's known defects, with evidence, correction rule and pre-publication checklist.

comex_resolve_code

Resolves country, HS code, transport mode and clearance unit (with airport/seaport/other classification).

The caveats that accompany the responses

id

Severity

Corrected?

via_contamination

critical

✅ automatic (cross-reference with the clearance point)

simplified_regime_absent

critical

❌ impossible — the data does not exist in the source

declared_not_audited

info

—

monthly_volatility

warning

❌ requires year-over-year comparison

About simplified_regime_absent: there are transport-mode codes for POSTAL and COURIER, but they are empty (13 records and 72 kg for China in all of 2026, versus ~180 million international parcels reported). Low-value shipments go through the simplified regime and do not enter trade statistics. Formal statistics and parcel volume are disjoint universes — do not add, do not compare arithmetically.

Verification

The aggregates were validated by cross-implementation: the same slice processed by a single awk pass over the raw CSV and by this server's SQL view produces identical figures to the last digit (349,250 records, 7 channels, freight and weight values).

npm test     # 12 testes da lógica de classificação e do registro de caveats

License and source

MIT. Data: Comex Stat, Foreign Trade Secretariat / Federal Revenue Service of Brazil (balanca.economia.gov.br) — public source, consulted at database build time.

Author: Luis Delfin



English

MCP server for Brazilian foreign-trade data — with the dataset's traps corrected in the response.

Four tools that don't lie, instead of forty that don't know.

The problem

An MCP server that merely exposes a dataset hands the agent a clean API to a wrong number. The plumbing doesn't know the field lies.

Brazil's official trade dataset (Comex Stat, published by the Foreign Trade Secretariat / Federal Revenue Service) has a defect no documentation warns about:

Filtering the transport-mode field by AIR returns 139.6 million kg of Chinese imports for Jan–Jul 2026. Cross-referencing those same records against their clearance point, only 34.0 million (24%) passed through an airport. The other 89.7 million cleared at seaports and consist of ammonium sulphate and phosphatic fertilisers — cargo that does not fly, at US$0.29/kg freight.

Uncorrected: air weight overstated 4.1× and freight per kg understated by 70%. The error is silent — nothing in the query flags it.

This server applies the correction, and returns the evidence for why it is needed.

Two guarantees

  1. Every response carries the known defects that apply to that query, with measured evidence and verification provenance.

  2. The critical correction is applied, not merely warned about. The air channel already means "air mode cleared at an airport". The contaminated block stays queryable as air_declared_at_port, deliberately — for anyone who wants to inspect it.

What the dataset has that published summaries discard

The import files carry VL_FRETE and VL_SEGURO — freight and insurance as declared to customs. It is the best systematic measure of realised cost available publicly, and almost nobody uses it.

China → Brazil, Jan–Jul 2026, corrected:

Channel

Weight (kg)

Freight US$/kg

Freight % of FOB

Value density

Air (airport-cleared)

33,993,130

10.81

9.37%

US$115.36/kg

Sea

16,074,641,185

0.142

5.68%

US$2.51/kg

Air costs 76× more per kilogram and only 1.65× more per dollar of goods. This corridor's modal split is not a freight decision — it is a value-density decision.

Install

Requires Node ≥ 22.5 (uses built-in SQLite — zero native dependencies, no node-gyp).

npm install && npm run build
npm run db:build -- --years 2025,2026        # fetches from the official source, builds SQLite

db:build pulls the files straight from balanca.economia.gov.br. No data is redistributed by this package — the database is built on your machine, always fresh from the source.

The four tools

Tool

What it does

comex_trade_flow

Value, weight and value density by year, month, country, HS code and channel. air is pre-corrected.

comex_freight_cost

Declared freight and insurance per channel: US$/kg and % of FOB. Imports only.

comex_data_caveats

The dataset's known defects, with evidence, correction rule and a pre-publication checklist.

comex_resolve_code

Resolves country, HS code, transport mode and clearance unit (with airport/seaport classification).

Verification

Aggregates were validated by cross-implementation: the same slice processed by a single awk pass over the raw CSV and by this server's SQL view produces identical figures to the last digit (349,250 records, 7 channels, freight and weight values).

npm test     # 12 tests covering the classification logic and the caveat registry

MIT. Data: Comex Stat, Brazilian Foreign Trade Secretariat / Federal Revenue Service. Author: Luis Delfin

Available Tools

4 tools
comex_data_caveatsA

Defeitos conhecidos do dataset do Comex Stat, cada um com evidencia quantificada, regra de correcao e procedencia da verificacao. Use ANTES de publicar qualquer numero derivado desta fonte — inclui o checklist de conferencia. Esta tool responde a pergunta que um wrapper de dados nunca responde: este campo quer dizer o que parece?

Inputs: id.

comex_freight_costA

Frete e seguro DECLARADOS a aduana, por canal de transporte — em US$/kg e como % do valor FOB. Vem dos campos VL_FRETE e VL_SEGURO dos arquivos de importacao, que os resumos publicados descartam: e a melhor medida sistematica de custo realizado disponivel publicamente. Somente importacao (os arquivos de exportacao nao trazem frete). O canal 'air' ja esta corrigido pelo ponto de despacho.

Inputs: ncm, years, months, group_by, +1 more.

comex_resolve_codeA

Resolve codigos oficiais para nomes e vice-versa: pais, NCM, modal de transporte (VIA) e unidade da Receita de despacho (URF, com sua classificacao aeroporto/porto/outra). Necessario porque o dataset e todo codificado.

Inputs: kind (required), query (required), limit.

comex_trade_flowA

Fluxo de comercio exterior do Brasil (valor, peso e densidade de valor) a partir dos microdados aduaneiros oficiais do Comex Stat. Filtra por ano, mes, pais, NCM e canal de transporte, e agrupa como pedido. O canal 'air' JA vem corrigido pelo ponto de despacho — o campo de modal do dataset e contaminado e nao pode ser usado cru. A resposta inclui sempre os caveats aplicaveis e a procedencia dos arquivos.

Inputs: ncm, flow, limit, years, +4 more.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 4 tools

    Disambiguation5/5

    The four tools have clearly distinct purposes: trade flow provides aggregated trade metrics, caveats explains data quality issues, freight cost focuses specifically on freight/insurance, and resolve_code handles code translation. There is no ambiguity in their scopes, and each tool addresses a separate aspect of working with the Comex Stat dataset.

    Naming Consistency4/5

    All tools share the consistent 'comex_' prefix, which helps identify the server's domain. However, the naming patterns vary: three use noun phrases (trade_flow, data_caveats, freight_cost) while one uses a verb (resolve_code). This is a minor deviation, but the uniform prefix and clear terminology keep the set predictable.

    Tool Count5/5

    With only four tools, the server is tightly scoped to the essential needs of querying Comex Stat data and understanding its caveats. Each tool is necessary and covers a distinct functional area, so the count is well-suited for the server's purpose without unnecessary bloat or trivial additions.

    Completeness4/5

    The tools cover the core workflows: querying trade flow, obtaining freight cost details, validating data quality through caveats, and resolving official codes. A minor gap is that freight data is only available for imports, but this is clearly stated and not a flaw in the tool design. Overall, the surface is sufficient for common analytical tasks.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      Access 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.
      530 npm
      4
      Apache 2.0
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables querying official Brazilian Federal Revenue data on foreign trade habilitation (Radar), allowing users to check habilitation status directly from the official source. Read-only MCP server with a single consultation tool.
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Brazilian foreign trade from MDIC/ComexStat -- exports and imports 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 commodity forecasts for hubs such as soybean, coffee and beef. 15 read-only tools, remote at https://mcp.kyrodata.com/mcp; official registry com.kyrodata/kyrodata.
      15
      1
      MIT