I. What is the Complete Loop?
A sale is not complete when the payment clears. In Latin America, a sale is complete when six things have happened: the payment settled, the government-mandated electronic invoice was issued and accepted by the tax authority, the shipping label was generated and the package handed to the carrier, the customer was notified on their preferred channel, the transaction was recorded in the company's ERP, and the bank account was reconciled.
Today, a human operator performs these six steps manually. They copy-paste data between dashboards. They type CPF numbers into fiscal portals. They screenshot tracking codes. Every order repeats the same work, and more orders mean hiring another person.
The Complete Loop hands this work to an AI agent equipped with the right MCP tools. Through CodeSpar, four of these steps (the charge, the invoice, the shipping label and the notification) are available as meta tools, subject to the credentials, permissions and approvals configured in your project; the agent or your code chains them. ERP registration and bank reconciliation have no meta tool today; Steps 5 and 6 below say what their MCP servers offer.
II. Why Latin America is different
If you've only built commerce in the US or Europe, Latin America will surprise you. The infrastructure is more structured, more regulated, and in many ways more agent-ready than what you're used to. Here's why.
Pix is not "Brazil's Venmo"
Pix is an instant payment system operated by BACEN (Brazil's central bank). It settled 64 billion transactions in 2024. It's free for individuals, nearly free for businesses, available 24/7/365, and settles in under 10 seconds. It's not a wallet or an app. It's a rail. Every bank in Brazil is required to support it.
For agents, Pix is structurally superior to card payments. No chargebacks (the payment is final once settled). No dispute windows. No PCI compliance requirements. No D+30 settlement delays. The agent generates a QR code, the customer scans it, and the money is in the merchant's account in seconds. The entire reconciliation step becomes trivial because the bank statement matches in real time.
NF-e is mandatory, not optional
In the US, invoicing is a business choice. In Brazil, it's a legal requirement. Every sale of a product (NF-e) or service (NFS-e) must be accompanied by an electronic invoice issued to SEFAZ (the state fiscal authority) and authorized in real time. The XML must be digitally signed with an A1 certificate. The tax codes (CFOP, NCM, ICMS, IPI, PIS, COFINS) must be correct. If they're wrong, SEFAZ rejects the invoice immediately.
This is actually good news for agents. The fiscal system is fully digital, fully structured, and fully validated. An agent that knows how to call the right API with the right parameters can issue a valid invoice. A human copying data between tabs is slow and makes errors.
SPED: the digital obligation system
SPED (Sistema Publico de Escrituracao Digital) is Brazil's comprehensive digital tax reporting framework. Every NF-e, financial transaction, and inventory movement must be reported through SPED. Companies file monthly obligations (EFD-ICMS/IPI, EFD-Contribuicoes) that cross-reference every invoice they've issued and received. If your NF-e data doesn't match your SPED filing, the Receita Federal (Brazil's IRS) notices.
This means that issuing the invoice correctly isn't just about the sale. It's about downstream compliance. An agent that issues NF-e must generate data that will survive SPED cross-referencing.
WhatsApp is the commerce channel
Over 500 million Latin Americans use WhatsApp daily. In Brazil, 96% of smartphones have WhatsApp installed. It's not a messaging app. It's the operating system for small business communication. Customers expect to receive order confirmations, payment receipts, tracking updates, and support interactions on WhatsApp. Email open rates in Brazil are 15-20%. WhatsApp message read rates exceed 90%.
Latin America's financial infrastructure — Pix, NF-e, SPED, WhatsApp — was built for the digital era. It was built for machines. It just hasn't been connected to agents yet. That's what CodeSpar does.
III. The 6 steps in detail
Each step in the Complete Loop corresponds to one MCP server and one underlying API. Let's go through each, and say which part CodeSpar does and which part the provider or your agent does.
Step 1: Charge via Pix — codespar_charge
The codespar_charge meta tool creates the Pix charge with the Pix provider connected in your project. In Brazil, the CodeSpar catalog routes Pix charges to Asaas, Mercado Pago, EBANX, Celcoin, Iugu and Stone. Zoop has an MCP server of its own (@codespar/mcp-zoop, with Pix, split-rule and marketplace tools), but codespar_charge does not route to it.
What CodeSpar does: sends the charge to the provider and returns it with the Pix copia e cola (pix_copy_paste), the QR code (pix_qr_code) and, when the provider has one, a hosted payment page (charge_url). When the provider's webhook reports the payment, CodeSpar publishes commerce.payment.succeeded to your triggers, and session.paymentStatus() reads the charge's status.
What stays with your agent: codespar_charge takes the amount, the currency, the method, a description, the buyer and an optional due date; it takes no idempotency key, expiration or split rule. A charge that expires unpaid is created again by the agent.
Step 2: Issue NF-e — @codespar/mcp-nfe-io
Our fiscal MCP server wraps the fiscal provider API (NFe.io in the current catalog), which handles NF-e (product invoices) and NFS-e (service invoices). The provider runs the document lifecycle: XML generation, digital signing with the company's A1 certificate, SEFAZ submission and authorization, PDF generation, correction letters and cancellation.
What the MCP server does: Takes structured input (customer data and items) and asks NFe.io for the NF-e; once SEFAZ authorizes it, the document carries its 44-digit access key. Each item's ICMS, IPI, PIS and COFINS classification (CST/CSOSN), the A1 certificate, the state tax registration and the tax regime must already be set up on the NFe.io company; NFe.io signs the XML with that certificate.
What to know:
• State-level ICMS variation: Brazil has 26 states plus the Federal District, each with different ICMS rates and rules. An interstate sale from SP to MG has a different base rate than SP to BA.
• Simples Nacional regime: Companies under the Simples Nacional tax regime have different NF-e requirements (CSOSN instead of CST, no ICMS highlighting). The tax regime is set on the NFe.io company.
• Rejection code handling: SEFAZ returns over 700 distinct rejection codes. An invoice status read (action: "status") reports a rejected NF-e as rejeitada, for the agent or the operator to correct the input.
A company that issues NF-e by hand looks up NCM codes, works out ICMS, checks the CFOP, uploads the certificate and submits to SEFAZ, for every invoice.
Step 3: Generate shipping label — @codespar/mcp-melhor-envio
The Melhor Envio MCP server wraps the Melhor Envio API, which quotes and generates labels across Brazilian carriers such as Correios and Jadlog. Its tools cover quotes, shipments, labels and tracking (calculate_shipping, create_shipment, generate_label, track_shipment).
What CodeSpar does: codespar_ship takes the origin, the destination and the items. In Brazil the catalog routes a quote to Melhor Envio's calculate_shipping, a label to create_shipment and tracking to track_shipment. CodeSpar fills Melhor Envio's sender and recipient fields from your request and from the shipper defaults saved on the connection. session.ship() returns the tracking code, the label URL, the carrier and the estimated delivery.
Step 4: Notify on WhatsApp — @codespar/mcp-z-api
The Z-API MCP server wraps the Z-API service, which sends WhatsApp messages from a number paired with your Z-API instance: text, images, documents and audio.
What the MCP server does: Sends the customer a WhatsApp text with the payment confirmation, the NF-e and the tracking code. codespar_notify sends it through Z-API's send-text: the number (country code and number, digits only) and the message.
Step 5: Register in ERP — @codespar/mcp-omie
The Omie MCP server (@codespar/mcp-omie) wraps the Omie ERP API. Its tools cover customers, products, sales orders, invoices, accounts receivable and payable, and financial movements (for example create_customer, create_order and get_financial).
What CodeSpar does: nothing on this step today. ERP registration has no meta tool, and Omie is not among the providers behind the meta tools. An agent that runs the Omie MCP server in its own MCP client can create the customer and the sales order; linking the order to the NF-e access key, the Pix ID and the tracking code, and not creating a customer twice, is that agent's job.
Step 6: Reconcile in banking — @codespar/mcp-stark-bank
The Stark Bank MCP server (@codespar/mcp-stark-bank) wraps the Stark Bank API. Stark Bank is a digital bank for businesses in Brazil, with an API for Pix, boleto and transfers. The server's tools read the balance, deposits and transfers (get_balance, list_deposits, get_deposit, list_transfers) and create transfers, boletos and Pix requests.
What CodeSpar does: bank reconciliation has no meta tool, and the brazilian preset in @codespar/sdk 0.16.11 does not load Stark Bank. Through CodeSpar, Stark Bank is a boleto rail for codespar_charge. Matching a deposit to its charge, and checking the net amount after fees, is the agent's or your code's job.
IV. Building a Complete Loop agent
Here's how to run the Complete Loop with the CodeSpar SDK. The example compiles against @codespar/sdk 0.16.11. It needs Node.js 20+; a CodeSpar account, which comes with a test project and a test key (csk_test_…) at Dashboard → API Keys; and a provider connected for each step: a charge provider for Pix, NFe.io for the NF-e (with the A1 certificate uploaded to your NFe.io company, the state tax registration, the tax regime and each item's tax classification), a carrier and Z-API for WhatsApp (an instance paired with your WhatsApp number, with its instance ID, instance token and Client-Token connected in the project). Under a test key, each call goes to its provider's test environment; NFe.io and Z-API have none, so the NF-e and the WhatsApp message are refused under a test key and run only in a live project, where they take real effect. It was not run end to end for this article.
session.send() hands the instruction to the agent, which calls the meta tools in dependency order (payment before invoice, invoice before shipping) and returns every call in run.tool_calls. Steps 5 and 6, ERP registration and bank reconciliation, have no meta tool today, so they are not in this run. For a fixed order, loop(session, { steps }) runs the steps you list, and onStepComplete fires after each one.
V. Error handling and retry
Commerce fails. Not sometimes — regularly. Payment gateways have outages. SEFAZ goes down for maintenance. Carrier APIs return 500s. A production-grade agent must handle every failure mode gracefully. Here's how the Complete Loop handles the most common failures.
When Pix times out
A Pix charge is created as pending; the money arrives when the customer pays. So the invoice waits for the payment: read the charge's status, and run the rest only when it says succeeded. If the customer never pays, nothing after the charge runs. Your application can then decide to create a new charge, send a reminder, or cancel the order.
When NF-e issuance fails
SEFAZ rejections are the most complex failure mode. Some are retryable (108: service unavailable). Some are data errors (301: invalid CNPJ for the emitter's state registration). Some are business rule violations (539: the NCM code doesn't match the CFOP).
A rejection like 108 (service unavailable) means SEFAZ was down; a data error or a rule violation needs the input corrected first. CodeSpar does not retry an NF-e on its own: a status read reports a rejected NF-e as rejeitada, and your agent or your operator decides.
What a WhatsApp send reports
When Z-API accepts the send-text request, codespar_notify returns the message id Z-API sent back, the channel, the recipient and the status QUEUED. QUEUED means only that Z-API accepted the request: it does not say the message was delivered or read. CodeSpar keeps no WhatsApp queue of its own and does not retry a message.
The Complete Loop is designed around a simple principle: a payment should never be lost because a downstream step fails. If the NF-e fails, the payment is still valid — your agent or your operator issues the invoice again once the input is corrected.
VI. Compliance: what the fiscal path does and what stays with you
Fiscal compliance in Brazil is not a feature. It's a hard requirement. Companies that don't issue NF-e face fines of 10-100% of the transaction value. Companies that issue incorrect NF-e face audits. Companies that file SPED reports inconsistent with their NF-e data get flagged by the Receita Federal.
What the fiscal path does today:
• Tax classification comes from you. Each item carries its ICMS, IPI, PIS and COFINS classification (CST/CSOSN); NFe.io refuses an NF-e without it.
• Certificate. A1 digital certificates expire annually. The certificate is uploaded to the NFe.io company, which signs with it; renewing it there before it lapses is the operator's job.
• Correction letters follow the rule. A correction letter (Carta de Correcao) is accepted only while the NF-e is authorized and within 30 days (720 hours) of authorization; an invoice status read reports whether that window is still open.
Compliance isn't a feature you add to an agent. The classification, the certificate and the registration stay with the company; the tools carry them to NFe.io and report what SEFAZ decided.
VII. The business case
The Complete Loop is not a technical exercise. It's a business transformation. We have not measured its savings yet, so this section quotes no figures.
Cost savings
The steps an operator repeats for every order (copying data between dashboards, typing CPF numbers, pasting tracking codes) are the steps the agent runs for the charge, the invoice, the label and the notification. That is the labor the Complete Loop takes off the operations team.
Speed
Manual processing waits for an operator to retype data between systems. With the Complete Loop, the four steps that have a meta tool take the time the APIs take, once the credentials, permissions and approvals they need are in place.
Error reduction
A person typing NF-e data makes mistakes (wrong ICMS, wrong CFOP, typos in customer data), and each rejected NF-e has to be investigated and resubmitted.
VIII. What's next
The Complete Loop today runs in Brazil. But Latin America is 33 countries, and commerce doesn't stop at borders. Here's what's coming.
Cross-border: BR → MX → CO
Mexico has CFDI (Comprobante Fiscal Digital por Internet) instead of NF-e, SPEI instead of Pix, and SAT instead of SEFAZ. Colombia has Factura Electronica and the DIAN. Each country has its own fiscal authority, invoice schema, and payment rails. We're building MCP servers for each, following the same pattern: one server per API, one meta tool per function, managed auth, structured errors.
The goal is a single loop(session, ...) call that works in any country. The agent doesn't need to know whether it's issuing an NF-e or a CFDI. It says "issue an invoice" and the meta tool routes to the correct country-specific server.
Multi-currency
Cross-border commerce requires currency conversion. A Brazilian seller shipping to Mexico needs to price in MXN, collect in MXN, convert to BRL, and report the transaction in both currencies for fiscal purposes. The Complete Loop will handle conversion rates (via BACEN's PTAX reference rate), FX fees, and dual-currency invoicing.
Escrow and dispute resolution
For marketplace scenarios, agents need escrow: hold the buyer's payment until the seller fulfills the order, then release. This is particularly important for cross-border transactions where trust is lower. The Complete Loop will support escrow as a first-class step, with configurable release triggers (delivery confirmed, inspection period elapsed, buyer approved).
The Complete Loop is a pattern, not a product. The pattern is: every step in a commercial transaction that a human does today, an agent will do tomorrow. We're building the tools that make that transition possible.
The bottom line
The Complete Loop is the answer to a simple question: what would it take for an AI agent to run a business in Latin America?
The answer is six MCP servers, each wrapping the API of one step of the commerce flow. Payments via Pix. Invoicing via NF-e. Logistics via carrier aggregation. Notifications via WhatsApp. ERP registration. Bank reconciliation.
All six are open source, MIT licensed and published on npm. Four of the steps are available as CodeSpar meta tools today.
If you're building an agent that needs to participate in commerce — not just talk about commerce, but actually charge customers, issue invoices, ship products, and reconcile bank accounts — this is the infrastructure layer you need.
Fabiano Cruz is co-founder of CodeSpar. The complete MCP server catalog is open source on GitHub and available on npm. To build your first Complete Loop agent, start with the payment agent tutorial.
Updated on 2026.10.07: the examples now compile against @codespar/sdk 0.16.11 and call the four steps that have a meta tool (charge, invoice, shipping and notification); ERP registration and bank reconciliation have none. The unmeasured timings are gone, and the catalog link points to the MCP servers' repository. Steps 1, 3, 5 and 6 now say what CodeSpar does and what the provider or the agent does, and the savings and time figures nobody measured are gone. A meta tool is described as available, not as autonomous execution, and the closing claim that the loop is live is gone.