mcp-comex-brasil
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., "@mcp-comex-brasilCompare freight cost per kg from China to Brazil by air and sea in 2026"
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.
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ÉREAreturns 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: @cyanheads/un-comtrade-mcp-server
The two guarantees
Every response carries the known defects that apply to that query, with measured evidence and verification provenance.
The critical correction is applied to the result, not merely warned about. The
airchannel already means "air mode cleared at an airport". The contaminated block remains queryable asair_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 SQLitedb: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,exportConfiguring 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 |
| Value, weight and value density by year, month, country, HS code and channel. The |
| Declared freight and insurance per channel: US$/kg and % of FOB. Imports only. |
| The dataset's known defects, with evidence, correction rule and pre-publication checklist. |
| Resolves country, HS code, transport mode and clearance unit (with airport/seaport/other classification). |
The caveats that accompany the responses
id | Severity | Corrected? |
| critical | ✅ automatic (cross-reference with the clearance point) |
| critical | ❌ impossible — the data does not exist in the source |
| info | — |
| 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 caveatsLicense 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
AIRreturns 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
Every response carries the known defects that apply to that query, with measured evidence and verification provenance.
The critical correction is applied, not merely warned about. The
airchannel already means "air mode cleared at an airport". The contaminated block stays queryable asair_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 SQLitedb: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 |
| Value, weight and value density by year, month, country, HS code and channel. |
| Declared freight and insurance per channel: US$/kg and % of FOB. Imports only. |
| The dataset's known defects, with evidence, correction rule and a pre-publication checklist. |
| 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 registryMIT. Data: Comex Stat, Brazilian Foreign Trade Secretariat / Federal Revenue Service. Author: Luis Delfin
Available Tools
4 toolscomex_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?
| Name | Required | Description | Default |
|---|---|---|---|
| id | No | Um caveat especifico. Vazio = todos. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of disclosure. It accurately describes a safe read-only behavior (retrieving caveat metadata) and discloses the internal structure of each result (evidence, correction rule, provenance). For a low-risk retrieval tool there is little behavioral hazard left uncovered.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is front-loaded with purpose and usage, and the essential guidance fits in three sentences. The closing rhetorical question adds rhetorical color but no operational information, making it mildly less economical than it could be.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple tool with one optional enum parameter and no output schema, the description is reasonably complete: it explains what the results contain, when to invoke it, and the overall QA intent. It does not specify the return format, but that is a minor gap for this information-retrieval use case.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%: the single 'id' parameter carries an enum and a clear explanation ('Um caveat especifico. Vazio = todos.'), so the schema already documents the parameter. The description adds no additional parameter-level detail, matching the baseline for high coverage.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool exposes known defects of the Comex Stat dataset, each with quantified evidence, a correction rule, and verification provenance. It positions itself against 'a data wrapper' generically, distinguishing its QA purpose from the sibling trade-flow/freight tools, though it never names those siblings explicitly.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
It gives explicit when-to-use guidance ('Use ANTES de publicar qualquer numero derivado desta fonte') and mentions a built-in conferencing checklist. However, it does not state when NOT to use it or name the alternatives (comex_trade_flow, comex_freight_cost) that it should be paired with.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| ncm | No | NCM completo ou prefixo. | |
| years | No | Anos, ex: [2025, 2026]. | |
| months | No | Meses 1-12. Vazio = todos. | |
| group_by | No | Dimensoes extra (o canal ja entra sempre). | |
| countries | No | Codigo, nome ou ISO3 do pais de origem. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the behavioral disclosure burden. It discloses the data source (VL_FRETE and VL_SEGURO fields), the fact it is import-only, that air is corrected by despatch point, and the output units (US$/kg and % of FOB). It does not describe the response shape or potential limitations like missing data or aggregation behavior, but the key behavioral facts are present. A score of 4 reflects that the description goes beyond a bare statement of function.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Three sentences, each earning its place: the first defines the product and units, the second explains provenance and why it is valuable, the third states constraints (import-only and air correction). It is front-loaded with the core definition and avoids redundant words. No fluff or repetition of schema content. This is concise and well-structured.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool has 5 parameters, no output schema, and no annotations. The description effectively communicates what the tool provides, but it does not describe the return format (e.g., whether it returns a table per channel, time series, or aggregated values). Since there is no output schema, the agent is left guessing at the response structure. While the core semantics are clear, the agent may need additional guidance on what to expect, making it incomplete for a complex data tool.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100% for all 5 parameters, so the baseline is 3. The description does not add parameter-specific semantics beyond the schema; it mentions the channel is always included (which relates to group_by) but does not explain details like how NCM prefix matching works or how to combine years/months. The schema already describes each parameter clearly. Thus the description adds no extra value for parameter understanding.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description names a specific resource (freight and insurance declared to customs by transport channel) and clearly distinguishes it from siblings by emphasizing it is the best systematic measure of realized cost. The verb is implicit ('provides') but the scope and source are explicit. It differentiates itself from comex_trade_flow (which likely covers flows) and comex_data_caveats (which explains caveats). This is a clear, distinct purpose.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description gives a clear constraint: only imports, with export files lacking freight. It also states the air channel is corrected, which is a usage detail. It implies the tool should be used when realized cost is needed ('melhor medida sistematica de custo realizado'), but it does not explicitly name alternatives or say when not to use it. Thus it provides clear context and a condition, but stops short of explicit when-to-use vs. when-not-to-use guidance.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| kind | Yes | Tipo de codigo. | |
| limit | No | Maximo de resultados (default 20). | |
| query | Yes | Codigo exato ou parte do nome. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full responsibility for behavioral disclosure. It mentions bidirectional resolution and the URF classification, which adds specific context. However, it does not disclose return format, error handling, or whether partial matches are supported. For a simple lookup this is adequate but not comprehensive.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two concise sentences. The first states the core function and lists the code types, the second provides the rationale. There is no wasted wording, and the key action is front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's simplicity (3 parameters, no output schema, no annotations), the description is essentially complete. It covers purpose, scope, and rationale. It could mention the return structure (e.g., list of matches) but the bidirectional resolver nature makes that non-critical for an agent to call it correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100%, so the baseline is 3. The description adds value by explaining what each kind represents (e.g., VIA is modal de transporte, URF includes classification aeroporto/porto/outra) and clarifies that query can be a code or a name. This enriches the parameter semantics beyond the schema alone.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific verb 'Resolve' with the resource 'codigos oficiais para nomes e vice-versa' and enumerates the exact code types (pais, NCM, VIA, URF) including URF's classification. This clearly distinguishes it from sibling tools like comex_trade_flow or comex_freight_cost, which handle completely different operations.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description gives clear context: the dataset is all coded, so the tool should be used whenever codes need translating. While it doesn't explicitly state alternatives or when not to use it, the sibling tools are not viable alternatives for this function, so the lack of exclusion is acceptable. The rationale is enough for an agent to infer when to invoke it.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| ncm | No | NCM completo (8 digitos) ou prefixo, ex: '8517' ou '85'. | |
| flow | No | Sentido do fluxo. Default: import. | |
| limit | No | Maximo de linhas (default 50, max 500). | |
| years | No | Anos, ex: [2025, 2026]. | |
| months | No | Meses 1-12. Vazio = todos. | |
| channel | No | Canal corrigido. 'air' = modal aereo despachado em aeroporto. 'air_declared_at_port' expoe o bloco contaminado, para inspecao. | |
| group_by | No | Dimensoes de agrupamento. Default: ['year']. | |
| countries | No | Codigo, nome (PT/EN) ou ISO3. Ex: ['160'] ou ['China']. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden. It discloses significant behavioral details: the 'air' channel is corrected by dispatch point because the dataset's modal field is contaminated and should not be used raw, and the response always includes applicable caveats and file provenance. This is valuable transparency about data quality and output structure. It does not cover all typical behaviors (e.g., read-only nature, pagination, rate limits), but the critical data correction and output caveat information is highly informative.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is concise, two sentences, and front-loaded with the main purpose. The first sentence states the core function, filters, and grouping; the second adds critical caveats about channel correction and response contents. There is no fluff, and the structure is efficient. It earns a 4 rather than 5 because it could be slightly more structured with bullets, but it is already clear and compact.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the complexity of 8 parameters (all optional) and no output schema, the description covers key aspects: it specifies the metrics returned, the correction for the 'air' channel, and that responses always include caveats and file provenance. This is fairly complete for a data retrieval tool. However, it does not mention typical response format details (e.g., units, pagination, or whether results are aggregated by default), and it omits any prerequisites like authentication. These are minor gaps but not critical.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so all 8 parameters already have explanatory text in the schema. The description text itself does not add new semantics for parameters beyond what the schema provides, even though the channel parameter's complex behavior is fully explained in the schema. According to the rubric, when schema coverage is high, the baseline is 3, and the description adds no additional value here.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool provides Brazil foreign trade flow data (value, weight, and value density) from official Comex Stat microdata, including filters and grouping. It mentions the specific resource and the metrics returned, making the purpose evident. It lacks an explicit verb like 'retrieve' but the noun-based phrasing is still clear. It is distinguishable from siblings, which focus on freight, code resolution, and caveats.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description does not mention when to use this tool versus the sibling tools (comex_data_caveats, comex_freight_cost, comex_resolve_code). It provides no explicit conditions for selecting this tool over alternatives, nor any 'when not to use' guidance. The only implicit hint is that it covers trade flows, but that is not sufficient for guiding tool selection.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
4 tool updates
v0.1.0- First observed
comex_data_caveats - First observed
comex_freight_cost - First observed
comex_resolve_code - First observed
comex_trade_flow
TDQS
Scored across 4 tools
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.
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.
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.
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
Related MCP Connectors
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.
Trade Intel MCP — Compound tools that chain Comtrade, Census, Treasury,
Comtrade MCP — UN Comtrade API for international bilateral trade data
Discover, resolve, and query official Brazilian economic data with semantic search and provenance.
Related MCP Servers
- AlicenseDqualityCmaintenanceServidor MCP para a API do ComexStat, ferramenta de acesso às estatísticas de comércio exterior do Brasil.207 npm2MIT
- AlicenseNot gradedqualityBmaintenanceAccess 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.64 npm3Apache 2.0
- AlicenseAqualityCmaintenanceAn MCP server for the U.S. Census Bureau's International Trade Data API, enabling queries of monthly export and import statistics by HS, NAICS, end-use, and other classifications, with tools for trade balance, top partners, and country code lookup.7Creative Commons Zero v1.0 Universal
- AlicenseNot gradedqualityCmaintenanceEnables 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