ab-comexstat-mcp-server
v1.0.3
Published
MCP Server for Brazilian Foreign Trade Data (ComexStat API) - Access to export/import statistics from MDIC
Downloads
362
Maintainers
Readme
🌉 ComexStat MCP Server
Official MCP Server for Brazilian Foreign Trade Data (ComexStat API)
Access comprehensive export and import statistics from Brazil's Ministry of Development, Industry and Commerce (MDIC) through the Model Context Protocol. Perfect for AI agents, data analysis, and trade research.
🎯 Features
- ✅ 100% Validated Data - Verified against official MDIC portal data
- 🌍 Complete Trade Statistics - Access to all Brazilian export/import data
- 🏛️ Multiple Classifications - NCM, BEC/CGCE, SITC/CUCI, ISIC support
- 🔍 Powerful Filtering - Filter by country, state, product, transport mode, and more
- 📊 Rich Metadata - Access to all available filter values and descriptions
- 🚀 High Performance - Built-in caching and optimized API calls
- 🌐 Multi-language - Support for Portuguese, English, and Spanish
- 🤖 AI-Friendly - Designed for use with Claude and other AI agents
📦 Installation
NPM
npm install -g ab-comexstat-mcp-serverFrom Source
git clone https://github.com/ab-company/comexstat-mcp-server.git
cd comexstat-mcp-server
npm install
npm run build🚀 Quick Start
Configuration for Claude Desktop
Add to your Claude Desktop config file (~/Library/Application Support/Claude/claude_desktop_config.json on macOS):
{
"mcpServers": {
"comexstat": {
"command": "npx",
"args": ["-y", "ab-comexstat-mcp-server"]
}
}
}Manual Server Start
ab-comexstat-mcp-serverOr from source:
npm run dev🔧 Available Tools
Metadata Tools
comexstat_list_filters
List all available filters for querying trade data.
Parameters:
module(optional): "general", "cities", or "historical"
Example:
{
"module": "general"
}comexstat_filter_values
Get all possible values for a specific filter.
Parameters:
filter: Filter ID (e.g., "country", "state", "ncm")module(optional): "general", "cities", or "historical"language(optional): "pt", "en", or "es"search(optional): Text to filter results
Example:
{
"filter": "country",
"language": "pt",
"search": "China"
}comexstat_hierarchies
List available product hierarchies.
Example:
{
"module": "general"
}Query Tools
comexstat_query_general
Query general trade data with powerful filtering options.
Parameters:
flow: "export" or "import"year_start: Start year (YYYY)year_end: End year (YYYY)filters(optional): Object with filter arrayscountry: Array of country IDsstate: Array of state IDsncm: Array of NCM codeschapter: Array of SH2 codesheading: Array of SH4 codessubHeading: Array of SH6 codes- And many more...
metrics(optional): Array of metrics to return (default: ["fob", "kg"])
Example - Fruit Exports from Pernambuco in 2021:
{
"flow": "export",
"year_start": 2021,
"year_end": 2021,
"filters": {
"state": ["26"],
"chapter": ["08"]
},
"metrics": ["fob", "kg"]
}Result:
{
"total_records": 39,
"total_fob": 247252107,
"total_kg": 201159037,
"records": [...]
}comexstat_query_cities
Query trade data by municipality.
Parameters:
flow: "export" or "import"year_start: Start yearyear_end: End yearfilters(optional): Includingcityfiltermetrics(optional): Metrics to return
comexstat_query_historical
Query historical trade data (earlier periods).
Parameters:
- Same as
comexstat_query_general
Workflow Tools
comexstat_workflow_product_research
Complete product research workflow with automatic ID lookup.
Parameters:
product_name: Product name to researchflow: "export" or "import"year_start: Start yearyear_end: End yearstate(optional): State name or code
Example:
{
"product_name": "coffee",
"flow": "export",
"year_start": 2020,
"year_end": 2023,
"state": "São Paulo"
}comexstat_workflow_country_analysis
Analyze trade with a specific country.
Parameters:
country_name: Country nameflow: "export" or "import"year_start: Start yearyear_end: End year
Utility Tools
comexstat_calculate_growth
Calculate growth rates between periods.
Parameters:
value_start: Starting valuevalue_end: Ending value
comexstat_format_currency
Format values as Brazilian currency (BRL).
Parameters:
value: Numeric valuedecimals(optional): Decimal places (default: 2)
📚 Usage Examples
Example 1: Find Top Coffee Exporting States
// Step 1: Find NCM code for coffee
const coffeeNCM = await comexstat_filter_values({
filter: "ncm",
search: "café"
});
// Step 2: Query exports by state
const exports = await comexstat_query_general({
flow: "export",
year_start: 2023,
year_end: 2023,
filters: {
ncm: ["09011100"]
},
metrics: ["fob", "kg"]
});Example 2: Analyze Trade with China
// Step 1: Find China's ID
const china = await comexstat_filter_values({
filter: "country",
search: "China"
});
// Step 2: Query exports to China
const exports = await comexstat_query_general({
flow: "export",
year_start: 2020,
year_end: 2023,
filters: {
country: ["160"]
}
});Example 3: Product Research Workflow (Automated)
// Single call handles everything
const research = await comexstat_workflow_product_research({
product_name: "soybean",
flow: "export",
year_start: 2020,
year_end: 2023,
state: "Mato Grosso"
});🗂️ Data Classifications
NCM Hierarchy (Nomenclatura Comum do Mercosul)
The NCM (Mercosur Common Nomenclature) is the primary product classification system used in Brazil and Mercosur countries.
| Level | Code Length | Example Code | Example Product | |-------|-------------|--------------|-----------------| | Section | Roman numeral | II | Vegetable products | | Chapter (SH2) | 2 digits | 08 | Edible fruits and nuts | | Heading (SH4) | 4 digits | 0806 | Grapes, fresh or dried | | SubHeading (SH6) | 6 digits | 080610 | Fresh grapes | | NCM | 8 digits | 08061000 | Fresh grapes |
Practical Example:
{
"section": "II - Vegetable Products",
"chapter": "08 - Edible fruits and nuts",
"heading": "0806 - Grapes, fresh or dried",
"subheading": "080610 - Fresh grapes",
"ncm": "08061000 - Fresh grapes"
}International Classifications - Equivalent Domains
Different classification systems view the same product from different perspectives:
Example Product: Fresh Coffee Beans
| Classification | Code | Category | Purpose | |----------------|------|----------|---------| | NCM | 09011100 | Coffee, not roasted, not decaffeinated | Product identification | | BEC/CGCE | 111 - Primary foods and beverages | Level 1: Primary goods | Economic use category | | SITC/CUCI | 071.11 - Coffee, not roasted | Division 071: Coffee and coffee substitutes | International trade comparison | | ISIC | 0128 - Growing of spices, aromatic, drug and pharmaceutical crops | Class level | Industry sector |
Example Product: Iron Ore
| Classification | Code | Category | Purpose | |----------------|------|----------|---------| | NCM | 26011100 | Non-agglomerated iron ores | Product identification | | BEC/CGCE | 21 - Industrial raw materials | Level 2: Raw materials | Economic use | | SITC/CUCI | 281.0 - Iron ore and concentrates | Group 281 | International comparison | | ISIC | 0710 - Mining of iron ores | Division 07 | Mining industry |
Example Product: Semiconductor Devices
| Classification | Code | Category | Purpose | |----------------|------|----------|---------| | NCM | 85423100 | Processors and controllers | Product identification | | BEC/CGCE | 42 - Parts and accessories of capital goods | Level 2: Capital goods | Economic use | | SITC/CUCI | 776.41 - Electronic integrated circuits | Subgroup 776.4 | Tech trade analysis | | ISIC | 2610 - Manufacture of electronic components | Division 26 | Electronics industry |
Classification Systems Details
BEC/CGCE (Broad Economic Categories)
Groups products by economic use rather than physical characteristics.
3-Level Hierarchy:
Level 1 (CGCE N1): Basic categories (6 groups)
1- Food and beverages2- Industrial supplies3- Fuels and lubricants4- Capital goods5- Transport equipment6- Consumer goods
Level 2 (CGCE N2): Intermediate categories (19 groups)
111- Primary foods21- Industrial raw materials42- Parts for capital goods
Level 3 (CGCE N3): Detailed categories (detailed breakdown)
Practical Use Case:
// Analyze what types of goods Brazil imports
const imports = await comexstat_query_general({
flow: "import",
year_start: 2023,
year_end: 2023,
filters: {
cgce_n1: ["4"] // Capital goods only
}
});SITC/CUCI (Standard International Trade Classification)
UN standard for comparing trade statistics internationally.
5-Level Hierarchy: | Level | Digits | Example | Description | |-------|--------|---------|-------------| | Section | 1 | 0 | Food and live animals | | Division | 2 | 07 | Coffee, tea, cocoa, spices | | Group | 3 | 071 | Coffee and coffee substitutes | | Subgroup | 4 | 071.1 | Coffee, not roasted | | Basic Heading | 5 | 071.11 | Coffee, not roasted, not decaffeinated |
Practical Use Case:
// Compare Brazil's coffee exports using international standard
const coffeeExports = await comexstat_query_general({
flow: "export",
year_start: 2020,
year_end: 2023,
filters: {
cuci_position: ["071"] // All coffee products
}
});ISIC (International Standard Industrial Classification)
Classifies products by the industry that produces them.
4-Level Hierarchy: | Level | Example | Description | |-------|---------|-------------| | Section | A | Agriculture, forestry and fishing | | Division | 01 | Crop and animal production | | Group | 012 | Growing of perennial crops | | Class | 0128 | Growing of spices, aromatic crops |
Practical Use Case:
// Analyze exports from manufacturing industries
const manufacturing = await comexstat_query_general({
flow: "export",
year_start: 2023,
year_end: 2023,
filters: {
isic_section: ["C"] // Manufacturing section
}
});Geographic Filters
- Country (País) - Trading partner countries
- Example:
"160"= China,"249"= United States
- Example:
- Economic Block (Bloco Econômico) - Trade blocks
- Example: European Union, Mercosur, NAFTA
- State (UF) - Brazilian states (27 states)
- Example:
"26"= Pernambuco,"35"= São Paulo
- Example:
- City (Município) - Brazilian municipalities
- Example:
"3550308"= São Paulo city
- Example:
Logistics
- Transport Mode (Via) - Maritime, air, road, rail, etc.
- Example:
"1"= Maritime,"4"= Air
- Example:
- URF - Customs clearance unit
- Example: Port of Santos, Guarulhos Airport
🤖 Python Agent (Experimental)
The repository includes an experimental Python agent (comex-agente/agente_comex_v3.py) that provides a standalone Python interface to interact with the MCP server.
Features
- Direct Python Integration - Use the MCP server from Python scripts
- Multi-step Workflows - Agent automatically searches for IDs before queries
- UTF-8 Encoding - Robust handling of Portuguese characters
- Ollama Support - Works with local LLMs via Ollama
Usage Example
from agente_comex_v3 import AgenteComex
# Initialize agent
agent = AgenteComex(model="ollama/qwen2.5:32b")
# Ask questions in natural language (Portuguese or English)
result = agent.query("Qual o volume de exportação de frutas de Pernambuco em 2021?")
print(result)
# Output:
# Pernambuco exportou US$ 247,252,107 em frutas em 2021
# Total: 201,159,037 kg
# Principais produtos:
# - Uvas: US$ 112,896,198 (45.7%)
# - Mangas: US$ 109,451,476 (44.3%)
# - Limões: US$ 17,767,313 (7.2%)Workflow Example
# Agent handles multi-step workflow automatically:
# 1. Search for "Pernambuco" → finds state code "26"
# 2. Search for "frutas" → finds chapter "08"
# 3. Query with filters: state=26, chapter=08
# 4. Format and return results
agent.query("Compare coffee exports from São Paulo vs Minas Gerais in 2023")
# Agent automatically:
# - Finds state IDs for both states
# - Finds NCM codes for coffee
# - Makes two queries
# - Compares results
# - Returns formatted comparisonConfiguration
The agent uses the MCP server as backend. Make sure the server is running or available:
# Terminal 1: Start MCP server
npm run dev
# Terminal 2: Run Python agent
python comex-agente/agente_comex_v3.pyRequirements
pip install openai # For Ollama compatibilityNote: This is an experimental feature. For production use, we recommend using the MCP server directly with Claude Desktop or other MCP-compatible clients.
🔄 Multi-Classification Query Examples
Example 1: Analyze Product by All Classifications
// Find coffee exports using different classification systems
const coffeeAnalysis = {
// By NCM (product-based)
ncm: await comexstat_query_general({
flow: "export",
filters: { ncm: ["09011100"] } // Coffee, not roasted
}),
// By BEC (economic use)
bec: await comexstat_query_general({
flow: "export",
filters: { cgce_n3: ["111"] } // Primary food products
}),
// By SITC (international standard)
sitc: await comexstat_query_general({
flow: "export",
filters: { cuci_position: ["071"] } // Coffee and substitutes
}),
// By ISIC (industry)
isic: await comexstat_query_general({
flow: "export",
filters: { isic_class: ["0128"] } // Growing spices/aromatic crops
})
};Example 2: Cross-Classification Analysis
// Compare capital goods (BEC) vs manufacturing exports (ISIC)
const capitalGoods = await comexstat_query_general({
flow: "export",
year_start: 2023,
year_end: 2023,
filters: {
cgce_n1: ["4"], // Capital goods (BEC)
isic_section: ["C"] // Manufacturing (ISIC)
}
});
// This finds manufactured capital goods - intersection of both classificationsExample 3: Industry Sector Analysis
// Analyze all electronics industry exports
const electronicsExports = await comexstat_query_general({
flow: "export",
year_start: 2020,
year_end: 2023,
filters: {
isic_division: ["26"] // Manufacture of computer, electronic products
}
});
// Compare with NCM classification for same products
const sameProductsNCM = await comexstat_query_general({
flow: "export",
year_start: 2020,
year_end: 2023,
filters: {
chapter: ["84", "85"] // Machinery and electrical equipment
}
});Example 4: Economic Use Pattern Analysis
// Track shift from raw materials to manufactured goods
const tradeStructure = {
rawMaterials: await comexstat_query_general({
flow: "export",
filters: { cgce_n2: ["21"] }, // Industrial raw materials
metrics: ["fob"]
}),
capitalGoods: await comexstat_query_general({
flow: "export",
filters: { cgce_n2: ["41", "42"] }, // Capital goods and parts
metrics: ["fob"]
}),
consumerGoods: await comexstat_query_general({
flow: "export",
filters: { cgce_n1: ["6"] }, // Consumer goods
metrics: ["fob"]
})
};
// Calculate export structure percentages
const total = rawMaterials.total_fob + capitalGoods.total_fob + consumerGoods.total_fob;
console.log({
rawMaterials: `${(rawMaterials.total_fob / total * 100).toFixed(1)}%`,
capitalGoods: `${(capitalGoods.total_fob / total * 100).toFixed(1)}%`,
consumerGoods: `${(consumerGoods.total_fob / total * 100).toFixed(1)}%`
});✅ Validation
This server has been 100% validated against official MDIC portal data:
PE 2021 Dataset (Data Accuracy)
- ✅ Validated 39 fruit products from Pernambuco 2021
- ✅ FOB value: US$ 247,252,107 (100% match with portal)
- ✅ Weight: 201,159,037 kg (100% match with portal)
SP 2025 Dataset (Field Mappings)
- ✅ Validated all 40 available columns
- ✅ 46,731 records analyzed
- ✅ 21 fields validated with 100% accuracy
- ✅ All international classifications validated
Full validation report: See VALIDATION_REPORT.md in the repository.
💼 Real-World Use Cases
Use Case 1: Market Research - Finding Export Opportunities
Scenario: A Brazilian fruit exporter wants to identify which countries import the most tropical fruits and analyze market potential.
// Step 1: Find tropical fruit NCM codes
const tropicalFruits = await comexstat_filter_values({
filter: "ncm",
search: "manga" // Mango
});
// Step 2: Get top importing countries
const topImporters = await comexstat_workflow_top_partners({
flow: "export",
year_start: 2023,
year_end: 2023,
filters: {
ncm: ["08045020"] // Fresh mangoes
},
top_n: 10
});
// Step 3: Analyze trends for top market (e.g., United States)
const usTrend = await comexstat_query_general({
flow: "export",
year_start: 2019,
year_end: 2023,
filters: {
country: ["249"], // United States
ncm: ["08045020"]
},
metrics: ["fob", "kg"]
});
// Calculate growth rate
const growth = await comexstat_calculate_growth({
value_start: usTrend.records[0].fob,
value_end: usTrend.records[4].fob
});
console.log(`US market grew ${growth.growth_rate}% in 5 years`);Use Case 2: Supply Chain Analysis - Import Dependencies
Scenario: Automotive industry analyst needs to track semiconductor import dependencies and identify supply chain risks.
// Step 1: Find semiconductor-related NCM codes
const semiconductors = await comexstat_filter_values({
filter: "heading",
search: "8542" // Electronic integrated circuits
});
// Step 2: Analyze import sources
const importSources = await comexstat_query_general({
flow: "import",
year_start: 2023,
year_end: 2023,
filters: {
heading: ["8542"],
isic_division: ["26"] // Electronics manufacturing
}
});
// Step 3: Check concentration risk (top 3 countries)
const topSuppliers = await comexstat_workflow_top_partners({
flow: "import",
year_start: 2023,
year_end: 2023,
filters: { heading: ["8542"] },
top_n: 3
});
// Calculate Herfindahl index for market concentration
const totalImports = importSources.total_fob;
const concentration = topSuppliers.records.reduce((sum, country) => {
const marketShare = country.fob / totalImports;
return sum + (marketShare ** 2);
}, 0);
console.log(`Market concentration index: ${(concentration * 100).toFixed(1)}%`);
console.log(`Risk level: ${concentration > 0.25 ? 'HIGH' : 'MODERATE'}`);Use Case 3: Regional Development - State Export Performance
Scenario: State government analyzing export competitiveness and diversification.
// Step 1: Get state's total exports by industry (ISIC)
const stateExports = await comexstat_query_general({
flow: "export",
year_start: 2023,
year_end: 2023,
filters: {
state: ["35"] // São Paulo
}
});
// Step 2: Analyze export diversification (how many product categories)
const productDiversity = await comexstat_query_general({
flow: "export",
year_start: 2023,
year_end: 2023,
filters: {
state: ["35"],
cgce_n1: ["4", "5", "6"] // Capital goods, transport, consumer goods
}
});
// Step 3: Compare with competing state
const competitorState = await comexstat_query_general({
flow: "export",
year_start: 2023,
year_end: 2023,
filters: {
state: ["41"] // Paraná
}
});
// Step 4: Calculate export sophistication (capital goods %)
const sophisticated = productDiversity.records.filter(r =>
r.cgce_n1 === "4" // Capital goods
).reduce((sum, r) => sum + r.fob, 0);
const sophisticationRate = (sophisticated / stateExports.total_fob * 100).toFixed(1);
console.log(`Export sophistication: ${sophisticationRate}% capital goods`);Use Case 4: Trade Policy Analysis - Tariff Impact Assessment
Scenario: Policy analyst evaluating impact of trade agreements on specific sectors.
// Step 1: Identify products under trade agreement
const euTrade = await comexstat_query_general({
flow: "export",
year_start: 2019,
year_end: 2023,
filters: {
block: ["15"], // European Union
cgce_n1: ["1"] // Food and beverages (agriculture sector)
}
});
// Step 2: Compare pre- and post-agreement periods
const preAgreement = euTrade.records.filter(r =>
r.year >= 2019 && r.year <= 2020
).reduce((sum, r) => sum + r.fob, 0) / 2; // Average
const postAgreement = euTrade.records.filter(r =>
r.year >= 2022 && r.year <= 2023
).reduce((sum, r) => sum + r.fob, 0) / 2; // Average
const impact = await comexstat_calculate_growth({
value_start: preAgreement,
value_end: postAgreement
});
console.log(`Agricultural exports to EU grew ${impact.growth_rate}%`);
console.log(`Absolute increase: ${await comexstat_format_currency(impact.absolute_change)}`);Use Case 5: Academic Research - Industry Competitiveness Study
Scenario: Researcher analyzing Brazil's competitiveness in high-tech manufacturing.
// Step 1: Define high-tech sectors (ISIC classification)
const highTechSectors = ["2610", "2620", "2630"]; // Electronics, communications, instruments
// Step 2: Get export data for these sectors
const highTechExports = await comexstat_query_general({
flow: "export",
year_start: 2015,
year_end: 2023,
filters: {
isic_class: highTechSectors
}
});
// Step 3: Compare with traditional manufacturing
const traditionalMfg = await comexstat_query_general({
flow: "export",
year_start: 2015,
year_end: 2023,
filters: {
isic_division: ["23", "24", "25"] // Non-metallic, metals, fabricated metal
}
});
// Step 4: Calculate revealed comparative advantage (RCA)
// RCA = (Product X exports / Total exports) / (World X exports / World total)
// Simplified using BEC classification
const capitalGoodsShare = await comexstat_query_general({
flow: "export",
year_start: 2023,
year_end: 2023,
filters: {
cgce_n1: ["4", "5"] // Capital goods + Transport equipment
}
});
const allExports = await comexstat_query_general({
flow: "export",
year_start: 2023,
year_end: 2023
});
const highTechShare = (capitalGoodsShare.total_fob / allExports.total_fob * 100).toFixed(1);
console.log(`High-tech share of exports: ${highTechShare}%`);Use Case 6: Business Intelligence - Competitor Analysis
Scenario: Brazilian soybean trader analyzing competitor states and destination markets.
// Step 1: Get soybean exports by state
const soybeanByState = await comexstat_query_general({
flow: "export",
year_start: 2023,
year_end: 2023,
filters: {
ncm: ["12019000"] // Soybeans
}
});
// Step 2: Identify top producing states
const topStates = await comexstat_workflow_top_partners({
flow: "export",
year_start: 2023,
year_end: 2023,
filters: {
ncm: ["12019000"]
},
top_n: 5
});
// Step 3: For each top state, analyze destination markets
const matogrossoMarkets = await comexstat_workflow_top_partners({
flow: "export",
year_start: 2023,
year_end: 2023,
filters: {
state: ["51"], // Mato Grosso
ncm: ["12019000"]
},
top_n: 10
});
// Step 4: Calculate market concentration
const topThreeShare = matogrossoMarkets.records
.slice(0, 3)
.reduce((sum, m) => sum + m.fob, 0);
const concentration = (topThreeShare / matogrossoMarkets.total_fob * 100).toFixed(1);
console.log(`Top 3 markets represent ${concentration}% of Mato Grosso soybean exports`);🧪 Testing
# Run all tests
npm test
# Run specific test suites
npm run test:metadata
npm run test:query
npm run test:workflow
npm run test:integration
# Run with coverage
npm run test:coverage
# Watch mode
npm run test:watchTest Results: 89/89 tests passing (100%) ✅
🏗️ Architecture
Components
- MCP Server - Implements Model Context Protocol
- Query Builder - Constructs API requests with proper filters
- Response Normalizer - Handles different API response formats
- Cache Layer - Built-in TTL caching for performance
- Type System - Full TypeScript support with Zod validation
Dependencies
@modelcontextprotocol/sdk- MCP SDKundici- Fast HTTP clientzod- Runtime type validation
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Setup
git clone https://github.com/ab-company/comexstat-mcp-server.git
cd comexstat-mcp-server
npm install
npm run build
npm testAutomated Validation
Use the validation script to test field mappings:
python scripts/validate_mappings.py <csv_file>📄 License
MIT License - see LICENSE file for details.
🙏 Acknowledgments
- MDIC (Ministério do Desenvolvimento, Indústria e Comércio) for providing the ComexStat API
- Anthropic for the Model Context Protocol
📞 Support
- Issues: GitHub Issues
- Email: [email protected]
- Website: aeonbridge.com
Sponsored by Aeon Bridge Co. 🌉
Building bridges between data and intelligence.
