Electronic invoicing in Latin America is mandatory, complex, and deeply specific to each country. This is not optional. In Brazil, every commercial transaction — every sale of a product, every service rendered, every interstate transfer of goods — requires an electronic invoice validated in real-time by a government fiscal authority. Non-compliance carries penalties of 1–10% of the transaction value, and repeat violations can result in CNPJ cancellation (the corporate death penalty in Brazil).
In Mexico, every transaction requires a CFDI validated by SAT. In Argentina, AFIP requires Factura Electronica for most B2B transactions and increasingly for B2C. Colombia, Chile, Peru, Ecuador — the entire region has converged on mandatory electronic invoicing, each with its own schemas, authorities, and failure modes.
No MCP server existed for any of these when we started. The agentic commerce stack assumed invoicing was someone else's problem. It isn't. It's the problem. An agent that can process a payment but can't issue the legally required invoice is an agent that exposes its operator to fiscal penalties on every transaction.
We built the MCP servers. Here's what we learned.
The Brazilian fiscal document landscape
Before diving into the technical implementation, you need to understand the scope of Brazil's electronic invoicing system. It is, without exaggeration, the most complex fiscal compliance regime in the world. The World Bank's "Doing Business" report consistently ranked Brazil last or near-last in tax compliance burden before the report was discontinued. Brazilian companies spend an average of 1,501 hours per year on tax compliance (World Bank data, 2020). The US average is 175 hours.
There isn't one type of electronic invoice in Brazil. There are five, each governed by different regulations, validated by different authorities, and required for different transaction types:
NF-e (Nota Fiscal Eletronica) — Merchandise
The NF-e covers the sale and transfer of physical goods. It is validated by SEFAZ (Secretaria da Fazenda) at the state level — meaning 27 different fiscal authorities, each running its own validation infrastructure. When a merchant sells a product, the NF-e must be transmitted to SEFAZ and receive an authorization protocol before the goods can be shipped. The XML schema is 300+ fields. The tax calculation involves ICMS (state value-added tax), IPI (federal excise), PIS/COFINS (federal social contributions), and potentially ICMS-ST (substitution tax regime). Getting any of these wrong results in rejection.
NFS-e (Nota Fiscal de Servicos Eletronica) — Services
NFS-e covers services. Here the complexity multiplies: NFS-e is governed at the municipal level. Brazil has 5,570 municipalities. Each municipality can (and many do) implement its own NFS-e schema, its own API, and its own validation rules. The ISS (Imposto Sobre Servicos) rate varies by municipality and service type, ranging from 2% to 5%. Some municipalities use the national ABRASF standard. Others use proprietary schemas. Some municipalities still don't have APIs at all — requiring manual entry into a web portal.
In 2023, the Brazilian government launched the NFS-e Nacional initiative to standardize municipal service invoices. Adoption is ongoing, but as of April 2026, approximately 2,800 municipalities have migrated to the national standard. The remaining 2,770 still use legacy systems.
NFC-e (Nota Fiscal de Consumidor Eletronica) — Consumer Retail
NFC-e is the digital equivalent of a cash register receipt. It's required for retail sales to final consumers. Like NF-e, it's validated by state-level SEFAZ, but with a simplified schema. NFC-e replaced the older ECF (Emissor de Cupom Fiscal) hardware-based system. The key difference from NF-e: NFC-e must be authorized in real-time at the point of sale, and if SEFAZ is offline, the merchant must operate in contingency mode (more on this below).
CT-e (Conhecimento de Transporte Eletronico) — Transport
CT-e documents freight transport. Required for any commercial shipment, CT-e identifies the shipper, the carrier, the origin, the destination, the cargo, and the associated NF-e. Without a valid CT-e, goods can be seized at state border checkpoints. This is particularly important for agent-driven commerce that includes fulfillment — the shipping step of the Complete Loop must generate a CT-e in addition to the shipping label.
MDF-e (Manifesto Eletronico de Documentos Fiscais) — Manifests
MDF-e is a manifest document that consolidates multiple CT-e and/or NF-e for a single shipment. Required for interstate transport, it enables fiscal authorities to verify that all goods in a truck have valid documentation. MDF-e must be issued before the vehicle departs and closed upon arrival at the destination.
Most developers outside Brazil have never heard of CT-e or MDF-e. But if your agent ships a physical product across state lines, you need both. Ignorance of the fiscal obligation doesn't prevent the penalty. It guarantees it.
SEFAZ integration: 27 authorities, 27 problems
SEFAZ is not a single system. It is 27 systems, one per Brazilian state, each with its own infrastructure, response times, and failure characteristics. Some states (SP, RJ, MG) run their own SEFAZ instances. Others delegate to the SVAN (SEFAZ Virtual do Ambiente Nacional) or SVRS (SEFAZ Virtual do Rio Grande do Sul). The routing is not intuitive.
Each SEFAZ instance has different performance characteristics. Sao Paulo's SEFAZ handles the highest volume (SP accounts for approximately 31% of Brazil's GDP) and is generally the most reliable, with average response times under 2 seconds. Smaller state SEFAZ instances can be significantly slower and less reliable. Mato Grosso's SEFAZ has been known to have response times exceeding 30 seconds during peak periods.
The contingency problem
SEFAZ goes offline. Not frequently, but regularly enough that any production system must handle it. When SEFAZ is unavailable, Brazilian law permits "contingencia" (contingency) operation — but the rules are specific and strict:
- EPEC (Evento Previo de Emissao em Contingencia). The merchant registers a summary of the NF-e with the national EPEC service. The full NF-e must be transmitted to SEFAZ within 7 days of service restoration. EPEC is the most common contingency mode.
- SVC-AN / SVC-RS (SEFAZ Virtual de Contingencia). Backup SEFAZ instances that can authorize NF-e when the primary state SEFAZ is down. Not all states have SVC agreements, and the switch must be made manually or via automated detection.
- FS-DA (Formulario de Seguranca). Paper-based contingency for extreme cases. Not relevant for agent automation, but it exists in the regulatory framework.
An agent issuing NF-e must detect SEFAZ unavailability (typically by catching HTTP 5xx responses or timeouts exceeding 30 seconds), automatically switch to contingency mode, issue the NF-e via EPEC or SVC, store the pending NF-e, and retransmit to the primary SEFAZ when it recovers. Our MCP server handles all of this. The agent sees a single codespar_invoice call that either succeeds or returns a specific error code.
Rejection codes: the undocumented minefield
SEFAZ returns rejection codes (motivos de rejeicao) when an NF-e fails validation. There are over 800 documented rejection codes. In practice, the ones you encounter most frequently are:
Rejection code 539 deserves special attention. It means the access key (chave de acesso) is a duplicate. The access key is a 44-digit number that uniquely identifies an NF-e. It includes the state code, emission date, CNPJ, NF-e model, series, NF-e number, emission type, numeric code, and a check digit. If any system generates two NF-e with the same access key (typically due to a race condition in the NF-e number sequence), SEFAZ rejects the second one with code 539. The MCP server must maintain an atomic counter for NF-e numbers to prevent this, even under concurrent agent workloads.
NCM classification (rejection codes 778, 611) is another major pain point. NCM (Nomenclatura Comum do Mercosul) is the product classification code used throughout Mercosul. Every product must have a valid NCM code, and the NCM determines the applicable tax rates (ICMS, IPI, PIS/COFINS) and the allowed CFOP (Codigo Fiscal de Operacoes e Prestacoes). An incorrect NCM means incorrect taxes, which means SEFAZ rejection or — worse — acceptance followed by a fiscal audit.
Getting NCM right is one of the hardest problems in Brazilian fiscal automation. There are over 13,000 active NCM codes. The mapping from product description to NCM is ambiguous (is a "wireless headphone" classified as 8518.30.00 or 8518.29.90?). The tax implications of the classification can vary by 10+ percentage points. Our MCP server includes an NCM suggestion tool that uses the product description and category to propose the most likely NCM code, but we always flag this as a field requiring merchant confirmation.
The Nuvem Fiscal MCP server: architecture
Nuvem Fiscal is a Brazilian fiscal API platform that abstracts SEFAZ communication, certificate management, and XML signing. We built our NF-e MCP server (@codespar/mcp-nuvem-fiscal) as a wrapper around Nuvem Fiscal's API, adding agent-specific logic on top.
Why Nuvem Fiscal and not direct SEFAZ integration? Three reasons:
- Certificate management. NF-e requires digital signatures using A1 or A3 certificates. A1 certificates are file-based (PFX format) and can be managed programmatically. A3 certificates require hardware tokens (smart cards or USB tokens) and are physically tied to a device. Nuvem Fiscal handles both, including certificate renewal and chain validation. Building this from scratch would add months.
- SEFAZ routing and failover. Nuvem Fiscal maintains the state-to-SEFAZ routing table and automatically handles contingency switching. They monitor all 27 SEFAZ instances and route to SVC when the primary is down.
- XML schema maintenance. The NF-e XML schema changes periodically (versioning managed by ENCAT). Nuvem Fiscal updates their library when schema versions change. We consume the updated API without modifying our MCP server.
The MCP server exposes 15 tools covering the full NF-e lifecycle:
The hard parts we solved
ICMS calculation: a problem with 27 * 27 * N dimensions
ICMS (Imposto sobre Circulacao de Mercadorias e Servicos) is Brazil's state-level value-added tax. It is, without qualification, the most complex tax calculation in any country we've worked with. The rate depends on:
- Origin state. Where the goods are being shipped from.
- Destination state. Where the goods are being shipped to.
- NCM code. The product classification, which determines whether the product has a special rate, an exemption, or falls under ICMS-ST (substitution tax regime).
- Buyer type. Whether the buyer is an ICMS contributor (registered company that collects ICMS) or a final consumer. This determines whether DIFAL (Diferencial de Aliquota) applies.
- Seller's tax regime. Whether the seller is under Simples Nacional (simplified tax regime for small businesses), Lucro Presumido (presumed profit), or Lucro Real (actual profit). Each regime has different ICMS calculation rules.
- Product-specific rules. Some products have specific ICMS rates set by CONFAZ agreements between states. Fuel, telecommunications, and energy have entirely different rate structures.
The interstate ICMS rate table alone has 729 cells (27 origin states * 27 destination states). Rates range from 4% (imported goods, interstate) to 25% (luxury goods, intrastate in some states). The DIFAL calculation for interstate sales to final consumers was reformed in 2024 and the transition rules run through 2029, with the destination state receiving an increasing share of the tax revenue each year.
Our MCP server doesn't attempt to calculate ICMS from first principles. It delegates to Nuvem Fiscal's tax engine, which maintains the rate tables and applies the correct calculation based on the transaction parameters. But the agent must provide the correct inputs — origin state, destination state, NCM, buyer contributor status — and the tool definition guides this with field descriptions and validation rules.
Simples Nacional: the deceptive simplification
Approximately 4.5 million Brazilian companies are enrolled in Simples Nacional, a simplified tax regime for micro and small businesses (annual revenue up to R$4.8 million). Simples Nacional consolidates multiple taxes into a single monthly payment. For NF-e purposes, Simples Nacional companies use CSOSN (Codigo de Situacao da Operacao no Simples Nacional) instead of CST (Codigo de Situacao Tributaria) for ICMS.
The deception is that "simplified" doesn't mean simple. Simples Nacional has six annexes, each with different tax rates and revenue brackets. The applicable annex depends on the company's primary activity (CNAE code). A software company pays different rates than a restaurant. A company that exceeded R$3.6 million in the previous 12 months enters a different rate bracket. Some Simples Nacional companies are required to pay ICMS-ST separately, despite being in the "simplified" regime.
SEFAZ rejection code 559 ("Informado CSOSN para emitente nao optante pelo Simples Nacional") is the second most common rejection we see in production. It means the agent used CSOSN codes on an NF-e for a company that is not enrolled in Simples Nacional. The reverse error — using CST codes for a Simples Nacional company — also triggers rejection. The MCP server validates the emitter's tax regime before generating the NF-e XML and selects the correct code system automatically.
Cost of manual compliance vs automated
We surveyed 47 Brazilian SMEs (annual revenue R$500K–R$10M) in Q1 2026 about their fiscal compliance workload. The results quantify the opportunity for automation:
The 62 hours per month breaks down as follows:
- Data entry: 28 hours. Manually entering transaction details into NF-e issuance systems. Product descriptions, NCM codes, quantities, values, buyer data.
- Error correction: 14 hours. Handling SEFAZ rejections, correcting data, resubmitting. The 4.2% rejection rate means roughly 1 in 24 NF-e requires rework.
- Reconciliation: 11 hours. Cross-referencing issued NF-e against payments received, identifying discrepancies, issuing correction letters (CC-e).
- Certificate management: 5 hours. Monitoring certificate expiration, renewing A1 certificates, coordinating A3 token access.
- Reporting: 4 hours. Generating SPED (Sistema Publico de Escrituracao Digital) files, EFD-ICMS/IPI reports, and other fiscal obligations.
The R$8,700 monthly cost includes the salary allocation for these hours plus accounting firm fees for tax calculation review. For a company processing 500 transactions per month, this works out to approximately R$17.40 per transaction in compliance overhead.
With automated NF-e issuance via the MCP server, the rejection rate drops to 0.3% (our production data across 14 merchants in Q1 2026). The manual hours drop to approximately 8 per month (primarily review and exception handling). The compliance cost drops to approximately R$1,200 per month. That's an 86% reduction in compliance cost and a 93% reduction in rejection-related rework.
Brazilian fiscal compliance isn't just a cost center. It's a bottleneck that throttles how fast a business can process transactions. An agent that automates NF-e issuance doesn't just save money. It removes the constraint that limits transaction throughput to however fast a human can type data into a form.
Mexico: CFDI via FacturAPI
Mexico's electronic invoicing system (CFDI — Comprobante Fiscal Digital por Internet) is the second-most complex in LatAm. Administered by SAT (Servicio de Administracion Tributaria), CFDI 4.0 has been mandatory since January 2023. Key differences from Brazil's NF-e:
- PAC intermediaries. Unlike Brazil where NF-e goes directly to SEFAZ, Mexican CFDI must be processed through a PAC (Proveedor Autorizado de Certificacion) — a SAT-authorized intermediary that validates, stamps (timbra), and stores the CFDI. There are approximately 70 authorized PACs.
- RFC validation. Every CFDI must include validated RFCs (Registro Federal de Contribuyentes) for both the issuer and the recipient. Since CFDI 4.0, the recipient's name must also match SAT's records exactly — including accents, capitalization, and abbreviations.
- Uso de CFDI codes. Each CFDI must specify how the recipient will use the invoice for tax purposes. There are 22 usage codes: G01 (merchandise acquisition), G03 (general expenses), S01 (no fiscal effect), etc. Using the wrong code doesn't cause rejection but can trigger an SAT audit for the recipient.
- Cancelation with acceptance. Since 2022, canceling a CFDI with a value exceeding MXN$1,000 requires the recipient's acceptance. The recipient has 72 hours to accept or reject the cancellation. If they don't respond, the cancellation is automatically accepted. This creates a 72-hour window of uncertainty that agents must handle.
The @codespar/mcp-facturapi server wraps FacturAPI, which handles PAC communication, timbrado (stamping), and XML generation:
Argentina: Factura Electronica via AFIP
Argentina's electronic invoicing is administered by AFIP (Administracion Federal de Ingresos Publicos). The system is somewhat simpler than Brazil's or Mexico's but has its own peculiarities:
- Three invoice types. Factura A (B2B between IVA Responsable Inscripto entities, includes IVA breakdown), Factura B (to final consumers or exempt entities, IVA included in price), and Factura C (issued by Monotributistas, the simplified tax regime). The type is determined by the fiscal status of both the issuer and the recipient.
- CAE authorization. Each invoice receives a CAE (Codigo de Autorizacion Electronico) from AFIP's web services. The CAE is a 14-digit authorization code with an expiration date. The invoice is not legally valid without a CAE.
- WSFE web service. AFIP's web service (WSFE) uses SOAP/XML, which is increasingly unusual in 2026. The authentication uses X.509 certificates and requires a two-step process: first authenticate with WSAA (Web Service de Autenticacion y Autorizacion) to get a token, then use that token with WSFE to authorize the invoice. The token expires after 12 hours.
- Monotributo complexity. Argentina's Monotributo is a simplified regime for small taxpayers. Monotributistas issue Factura C and have monthly revenue limits that vary by category (A through K). If a Monotributista exceeds their category limit, they're automatically reclassified, which changes their invoicing requirements. The MCP server tracks the issuer's Monotributo category and warns when approaching the limit.
The agent experience: one tool call
From the agent's perspective, all of this complexity is invisible. The agent calls codespar_invoice with the transaction details. The SDK determines the country from the recipient's document type (CPF/CNPJ = Brazil, RFC = Mexico, CUIT = Argentina), routes to the correct MCP server, and handles the entire issuance flow.
Behind that single tool call, the MCP server:
- Validated the CNPJ at Receita Federal and determined the emitter's tax regime
- Determined that the recipient is a final consumer (CPF, not CNPJ) and set the operation accordingly (CFOP 5102 for intrastate, 6102 for interstate)
- Calculated ICMS based on origin state (SP), destination state (SP), NCM (8518.30.00), and buyer type (final consumer)
- Calculated PIS and COFINS based on the emitter's tax regime
- Generated the 44-digit access key with atomic NF-e number sequencing
- Built the 300+ field XML document
- Signed the XML with the emitter's A1 certificate
- Transmitted to SP SEFAZ (nfe.fazenda.sp.gov.br)
- Received the authorization protocol
- Generated the DANFE PDF
- Stored the signed XML for the 5-year legal retention period
The regulatory moat: why this complexity is our advantage
Every conversation about LatAm fiscal compliance starts with someone saying "this is too complex." They're right. It is. And that's precisely why it's a defensible competitive advantage.
The complexity of Brazilian NF-e issuance isn't going to be simplified. ENCAT (the national committee that governs NF-e) has been adding fields and rules for 18 years. There's no political appetite for simplification because the complexity serves a purpose: it enables the Brazilian government to track every commercial transaction in real-time and detect tax evasion with high accuracy. Brazil's electronic invoicing system collects more tax revenue per GDP point than any comparable system in the world.
This means:
- The barrier to entry is high. Any new entrant in LatAm agentic commerce must solve NF-e, CFDI, and Factura Electronica. There is no shortcut. You can't "move fast and break things" with fiscal compliance — breaking things means fiscal penalties and potentially criminal liability for the merchant.
- Domain knowledge accumulates. Every SEFAZ rejection we encounter, every edge case we handle, every state-specific quirk we discover becomes encoded in the MCP server. This knowledge compounds over time and is extremely difficult for competitors to replicate without going through the same production-hardening process.
- US-first platforms won't do this. Stripe, Shopify, and other US-first commerce platforms have been in Brazil for years. None of them have built comprehensive NF-e issuance. It's not that they can't — it's that the ROI calculation doesn't justify the engineering investment for a US-focused company. For us, it's the core product.
The complexity of Latin American fiscal compliance isn't a bug. It's a 10-foot wall around a market of 660 million people. We spent months climbing it. Now we're on the other side, and the wall protects us too.
What's next: tax reform and NF-e 5.0
Brazil's historic tax reform (Emenda Constitucional 132/2023) will replace ICMS, ISS, IPI, PIS, and COFINS with two new taxes: IBS (Imposto sobre Bens e Servicos) and CBS (Contribuicao sobre Bens e Servicos). The transition runs from 2026 to 2033. This will fundamentally change the NF-e XML schema and tax calculation logic.
For manual compliance processes, the tax reform will be chaos. For automated systems like our MCP server, it's a schema update. The agent still calls codespar_invoice with the same parameters. The tax calculation engine underneath adapts. The complexity of the transition — dual-track tax calculation during 2026–2033, new product classification codes, new rate tables — is exactly the kind of problem that automated systems handle better than humans.
The NF-e format itself is expected to evolve to version 5.0 to accommodate the new tax structure. ENCAT has signaled that NF-e 5.0 will include IBS and CBS fields alongside the legacy ICMS/PIS/COFINS fields during the transition period. Our MCP server will support both schemas simultaneously, selecting the correct version based on the emission date and the applicable tax regime.
The SEFAZ rejections aren't documented in any official manual. You encounter them in production, one at a time, each one teaching you something about the gap between the specification and reality. A CNPJ-ME (Microempresa) gets rejected differently than a CNPJ-LTDA. A state transition from SP to RJ has different ICMS rules than SP to MG. An NFS-e in Sao Paulo municipality uses a different schema than an NFS-e in Campinas, 90 kilometers away.
This knowledge is now encoded in the tool definitions, input validation, and error handling of each MCP server. It's not documentation. It's not a wiki page. It's working code that prevents errors before they happen and handles them gracefully when they do. Every month of production operation adds more edge cases, more state-specific rules, more rejection code handlers. The moat deepens.