Skip to main content
All posts
Deep Dive

The Complete Loop: How AI Agents Run a Business in Latin America

Charge via Pix. Issue the NF-e. Generate the shipping label. Notify on WhatsApp. Register in the ERP. Reconcile in banking. Six systems, six APIs, zero humans, under five seconds. This is the definitive guide to the Complete Loop.

FC
Fabiano Cruz
Co-founder, CodeSpar
Deep Dive
2026.04.15
22 min

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. For a small e-commerce business processing 50 orders a day, this is 15-45 minutes of manual work per order. That's 12-37 hours a day of operational labor. More orders than that, and you hire another person.

The Complete Loop eliminates all of it. An AI agent, equipped with the right MCP tools, executes all six steps autonomously. Payment confirmation triggers invoicing. Invoicing triggers shipping. Shipping triggers notification. Everything flows into the ERP and reconciles against the bank. No human touches the process.

The Complete Loop
01
Charge via Pix
@codespar/mcp-zoopZoop / Asaas
340ms
02
Issue NF-e
@codespar/mcp-nuvem-fiscalNuvem Fiscal / SEFAZ
1.2s
03
Generate shipping label
@codespar/mcp-melhor-envioMelhor Envio
890ms
04
Notify on WhatsApp
@codespar/mcp-z-apiZ-API / Meta Business
210ms
05
Register in ERP
@codespar/mcp-omieOmie ERP
580ms
06
Reconcile in banking
@codespar/mcp-stark-bankStark Bank
440ms
6APIs orchestrated
<5send to end
0human steps

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 perfectly valid invoice in under 2 seconds. A human copying data between tabs takes 5-10 minutes and makes errors on roughly 3% of invoices.

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. This is why CodeSpar's Nuvem Fiscal MCP server calculates taxes correctly — not as a convenience, but as a compliance requirement.

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, one underlying API, and a specific set of edge cases that the server handles. Let's go through each.

Step 1: Charge via Pix — @codespar/mcp-zoop

The Zoop MCP server wraps the Zoop payment gateway API, which itself connects to BACEN's SPI (Sistema de Pagamentos Instantaneos). The server exposes tools for creating Pix charges, checking payment status, creating refunds, managing Pix keys, and listing transactions.

What the MCP server does: Generates a Pix payload (EMV format), creates a QR code, registers a webhook listener for payment confirmation, and returns the transaction status. It also supports Pix Cobranca (charges with expiration) and Pix Saque/Troco (cash withdrawals at point of sale).

Edge cases handled:

Duplicate charges: The server uses idempotency keys. If the agent retries a charge (because it didn't get a response), Zoop returns the existing charge instead of creating a duplicate.

Expired charges: Pix charges have a configurable expiration (default 30 minutes). If the customer doesn't scan in time, the server returns PAYMENT_EXPIRED and the agent can create a new charge.

Pix key validation: A Pix key can be registered but deactivated, returning a 200 status with a silent failure. The server validates key status before generating the charge.

Split payments: For marketplace scenarios, the server supports split rules that divide the payment between multiple receivers (seller, platform, logistics partner).

Step 2: Issue NF-e — @codespar/mcp-nuvem-fiscal

The Nuvem Fiscal MCP server wraps the Nuvem Fiscal API, which handles NF-e (product invoices), NFS-e (service invoices), NFC-e (consumer invoices), and CT-e (transport invoices). The server manages the full lifecycle: XML generation, digital signing, SEFAZ submission, authorization, PDF generation, and cancellation.

What the MCP server does: Takes structured input (emitter CNPJ, items with NCM codes, customer data) and produces a SEFAZ-authorized NF-e with a valid 44-digit access key. It calculates ICMS based on origin/destination states, applies IPI/PIS/COFINS rates, selects the correct CFOP based on transaction type, and handles the A1 certificate signing.

Edge cases handled:

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. The server maintains an up-to-date rate table and applies the correct calculation automatically.

Simples Nacional regime: Companies under the Simples Nacional tax regime have different NF-e requirements (CSOSN instead of CST, no ICMS highlighting). The server detects the regime from the emitter's CNPJ registration and adjusts the XML accordingly.

SEFAZ downtime: SEFAZ occasionally goes down for maintenance (usually late-night). The server detects unavailability (HTTP 108 or connection timeout), switches to SEFAZ contingency (SVC-AN or SVC-RS), and queues the NF-e for resubmission when the primary service recovers.

Rejection code handling: SEFAZ returns over 700 distinct rejection codes. The server maps the most common ones (duplicated NF-e number, invalid CNPJ, incorrect ICMS calculation) to human-readable error messages and suggests corrective actions.

Why NF-e matters for agents

A company that issues 100 NF-e per day manually spends roughly 5-8 minutes per invoice: looking up NCM codes, calculating ICMS, checking CFOP, uploading the certificate, and submitting to SEFAZ. That's 8-13 hours of manual labor per day. With CodeSpar, the same 100 invoices take under 3 minutes total. The error rate drops from ~3% (human average) to <0.1% (MCP server with validation).

Step 3: Generate shipping label — @codespar/mcp-melhor-envio

The Melhor Envio MCP server wraps the Melhor Envio API, which aggregates quotes and label generation across Brazilian carriers: Correios (SEDEX, PAC), Jadlog, Loggi, Azul Cargo, and others. The server handles shipping quotes, label generation, tracking, and return labels.

What the MCP server does: Takes origin CEP, destination CEP, package dimensions, and weight. Returns quotes from all available carriers sorted by price and delivery time. Generates the label, returns the tracking code, and monitors delivery status via webhooks.

Edge cases handled:

Schema inconsistencies: Melhor Envio returns different response schemas for different carriers. Correios responses include AR (Aviso de Recebimento) fields. Jadlog responses include distribution center codes. The server normalizes these into a consistent schema.

Address validation: Brazilian CEP codes map to specific streets, but the customer's address might not match the CEP database. The server validates and corrects addresses using the ViaCEP API before generating labels.

NF-e cross-reference: Shipping labels for physical products require the NF-e access key. The server validates that the NF-e was authorized before generating the label. If the NF-e is pending, it waits.

Correios outages: Correios' API has periodic availability issues. The server detects this and falls back to alternative carriers in the quote list.

Step 4: Notify on WhatsApp — @codespar/mcp-z-api

The Z-API MCP server wraps the Z-API service, which provides a REST interface to the WhatsApp Business API (via Meta) and WhatsApp Web protocol. The server supports sending text messages, template messages, media (images, PDFs, documents), and interactive messages (buttons, lists).

What the MCP server does: Sends the customer a WhatsApp message with the payment confirmation, NF-e PDF, and tracking code. For template messages, it handles variable substitution and language selection. For session messages (within the 24-hour window), it supports freeform text.

Edge cases handled:

Out-of-order webhooks: Under high load, Z-API webhooks can arrive out of order (delivered before sent). The server uses message IDs and timestamps to reconstruct the correct sequence.

Rate limiting: Meta's Business API enforces per-phone rate limits. The server maintains a token bucket per WhatsApp number and queues messages when the limit is reached, draining the queue as capacity frees up.

Template approval: Template messages must be pre-approved by Meta. The server checks template status before sending and falls back to a session message if the template is pending approval.

Number format normalization: Brazilian phone numbers can be provided in multiple formats (with/without country code, with/without 9th digit). The server normalizes to E.164 format before sending.

Step 5: Register in ERP — @codespar/mcp-omie

The Omie MCP server wraps the Omie ERP API. Omie is the most popular cloud ERP for small and medium businesses in Brazil, with over 200,000 customers. The server handles customer records, product catalog, sales orders, accounts receivable, accounts payable, and financial movements.

What the MCP server does: Creates a sales order in Omie linked to the NF-e access key, the Pix transaction ID, and the shipping tracking code. Updates accounts receivable when the payment confirms. Creates or updates the customer record if it doesn't exist.

Edge cases handled:

Customer deduplication: Omie identifies customers by CPF/CNPJ. The server checks if the customer already exists before creating a new record, preventing duplicates that break financial reporting.

Product mapping: The server maps product SKUs from the e-commerce platform to Omie's internal product codes. If a product doesn't exist in Omie, it creates it with the correct NCM and fiscal configuration.

API rate limits: Omie enforces strict per-app rate limits (5 requests/second). The server queues requests and processes them within the limit to avoid HTTP 429 errors.

Step 6: Reconcile in banking — @codespar/mcp-stark-bank

The Stark Bank MCP server wraps the Stark Bank API. Stark Bank is a digital bank for businesses in Brazil, offering programmatic access to Pix, boleto, transfers, and statement reconciliation. The server handles balance queries, transfer creation, statement retrieval, and automatic reconciliation.

What the MCP server does: Matches the Pix incoming payment in the bank statement with the Zoop transaction ID. Confirms that the net amount (after Zoop's processing fee) matches the expected value. Marks the transaction as reconciled in both the banking system and the ERP.

Edge cases handled:

Fee discrepancies: Zoop charges a percentage fee on each transaction. The server calculates the expected net amount and flags discrepancies above a configurable threshold.

Timing gaps: The Pix settlement hits the bank account almost instantly, but the statement API may have a delay of a few seconds. The server retries reconciliation with exponential backoff.

Partial payments: If a customer makes a partial payment (possible with Pix manual entry), the server detects the underpayment and creates a follow-up charge for the remaining amount.

IV. Building a Complete Loop agent

Here's how to run the Complete Loop with the CodeSpar SDK. This is the same code pattern used in production deployments.

import { CodeSpar } from "@codespar/sdk";

const codespar = new CodeSpar({
  apiKey: process.env.CODESPAR_API_KEY,
});

// Create a session with all 6 Brazilian commerce servers
const session = await codespar.session.create({
  userId: "user_abc123",
  preset: "brazilian",
});

// Execute the Complete Loop
const result = await session.loop({
  instruction: `
    Process order #4521 for Maria Silva (CPF 123.456.789-00).

    1. Charge R$247.90 via Pix for "2x Wireless Headphones".
    2. After payment confirms, issue NF-e from our
       CNPJ 12.345.678/0001-99 (Simples Nacional, IE 123456789).
       NCM 85183000, CFOP 5102 (sale within state).
    3. Generate shipping label: 800g package, 25x15x10cm,
       from CEP 01310-100 (SP) to CEP 22041-080 (RJ).
       Use the cheapest carrier with delivery under 5 days.
    4. Send WhatsApp to +5511999887766 with payment receipt,
       NF-e PDF, and tracking code.
    5. Register sale in Omie ERP.
    6. Reconcile payment in Stark Bank.
  `,
  onStep: (step) => {
    console.log(
      `[${step.index}/6] ${step.server} - ${step.status}`
      + (step.durationMs ? ` (${step.durationMs}ms)` : "")
    );
  },
});

console.log(`Complete Loop finished in ${result.totalTime}`);
console.log(`Payment: ${result.payment.status}`);
console.log(`Invoice: ${result.invoice.accessKey}`);
console.log(`Shipping: ${result.shipping.trackingCode}`);
console.log(`WhatsApp: ${result.notification.status}`);
console.log(`ERP: ${result.erp.orderId}`);
console.log(`Reconciliation: ${result.reconciliation.status}`);

The session.loop() method parses the instruction, determines the dependency graph (payment before invoice, invoice before shipping, etc.), executes each step through the corresponding meta tool, and aggregates the results. The onStep callback fires after each step completes, giving you real-time progress.

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

If the customer doesn't scan the QR code within the expiration window, the charge expires. The loop doesn't crash. It returns a partial result with payment.status: "expired" and stops execution. Your application can then decide to create a new charge, send a reminder, or cancel the order.

const result = await session.loop({
  instruction: "...",
  onError: (error, context) => {
    if (error.code === "PAYMENT_EXPIRED") {
      // The loop stops here. No invoice, no shipping.
      // You decide what happens next.
      return "stop"; // or "retry" to create a new charge
    }
    if (error.code === "SEFAZ_UNAVAILABLE") {
      // Invoice step failed, but payment succeeded.
      // Continue with shipping, retry invoice later.
      return "skip";
    }
    return "stop"; // default: stop the loop
  },
});

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).

The MCP server classifies each rejection code into three categories: retryable (try again in 30 seconds), fixable (the input data needs correction), and fatal (the operation cannot succeed with these parameters). For retryable errors, the server handles retries internally. For fixable errors, it returns the rejection reason and a suggested correction. For fatal errors, it returns a clear error message.

When WhatsApp rate-limits you

Meta enforces tiered rate limits on the WhatsApp Business API based on your phone number's quality rating and messaging volume. If you hit the limit, the Z-API MCP server queues the message and delivers it when the window opens. The onStep callback reports status: "queued" instead of status: "sent". The message will be delivered, just not immediately.

Resilience philosophy

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 — the invoice can be retried. If WhatsApp is rate-limited, the customer gets notified later. If the ERP is down, the transaction is queued. The loop degrades gracefully, step by step, and every partial result is persisted for retry.

VI. Compliance: how CodeSpar handles fiscal obligations

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.

CodeSpar's approach is to make compliance automatic. The Nuvem Fiscal MCP server encodes the fiscal rules into the tool logic:

Tax calculation is automatic. You provide the items with NCM codes and the origin/destination states. The server calculates ICMS, IPI, PIS, and COFINS based on the current rates for that product category and state pair.

CFOP selection is guided. The server validates that the CFOP matches the transaction type. A 5102 (sale within state) cannot be used for an interstate transaction. The server catches this before submission.

Certificate management is handled. A1 digital certificates expire annually. The server tracks expiration dates and alerts before the certificate lapses. It also handles certificate chain validation to prevent signing failures.

Cancellation follows the rules. NF-e can only be cancelled within 24 hours of authorization (in most states). After that, you need to issue a correction letter (Carta de Correcao) or a return NF-e. The server enforces these time windows.

Compliance isn't a feature you add to an agent. It's a constraint you encode into the tools the agent uses. Get the tools right, and the agent is compliant by default.

VII. The business case

The Complete Loop is not a technical exercise. It's a business transformation. Here are the numbers.

Cost savings

A human operations specialist in Brazil earns R$3,000-5,000/month. They can process 40-60 orders per day at 15-45 minutes per order. A Complete Loop agent processes an order in under 5 seconds. One agent replaces the operational labor of 3-5 human operators. For a business processing 200 orders/day, that's R$9,000-25,000/month in labor savings.

The CodeSpar Pro tier costs $49/month for 25,000 tool calls. A Complete Loop of 6 calls per order means 4,166 orders per month. At 200 orders/day, that's roughly $49/month for what used to cost R$15,000+/month in labor.

Speed

Manual processing: 15-45 minutes per order. Complete Loop: under 5 seconds. That's not an incremental improvement. It's a category change. Orders placed at 11pm are processed at 11pm. Not the next morning when the operations team arrives.

Error reduction

Human NF-e error rate: ~3% (wrong ICMS, wrong CFOP, typos in customer data). Agent NF-e error rate: <0.1% (structured input, validated before submission). Each rejected NF-e costs 5-15 minutes to investigate and resubmit. At 100 invoices/day with a 3% error rate, that's 3 resubmissions costing 15-45 minutes of extra labor daily. The agent eliminates this entirely.

98%labor cost reduction
180xfaster processing
30xfewer NF-e errors

VIII. What's next

The Complete Loop today covers Brazil end to end. 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 session.loop() 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 a production API that handles one step of the commerce flow. Payments via Pix. Invoicing via NF-e. Logistics via carrier aggregation. Notifications via WhatsApp. ERP registration. Bank reconciliation. Each server handles the edge cases, the compliance requirements, and the regional quirks that make Latin American commerce uniquely challenging.

CodeSpar provides all six. Open source. MIT licensed. Published on npm. Production-ready 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.

The Complete Loop is live. The agents are running. The era of manual order processing is ending.

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.