Skip to main content
All posts
Guides

10 things you can build with CodeSpar today

An autonomous order fulfillment agent. A WhatsApp commerce bot. A cross-border payment orchestrator. Marketplace split payments. Subscription billing with dunning. Ten production-ready use cases with the CodeSpar MCP catalog and SDK. Each one is a business case, not a demo.
FC
Fabiano Cruz
Co-founder, CodeSpar
Guides
2026.03.06
22 min

These are not hypothetical. Each use case uses published MCP servers and the @codespar/sdk. The code examples are real. Install the packages and run them.

But more importantly, each use case is a business case. We include the problem (with numbers), the agent solution (with code), the result (with measurable outcomes), and what happens when things go wrong (because they will). If you are a founder, CTO, or product lead evaluating whether agent commerce infrastructure is worth building on, this post is designed to answer that question with specifics, not hand-waving.

A note on the numbers

The market data cited below comes from IBGE, Banco Central, ABCOMM, Sebrae, and Correios public reports. The performance claims come from internal testing on the CodeSpar Sandbox environment. Your results will vary based on API latency, provider uptime, and transaction volume. We are being conservative in our estimates.

1

Autonomous Order Fulfillment Agent

The business problem

A typical Brazilian D2C brand processing 200 orders per day employs 2-3 people full-time on post-sale operations: charging the customer, issuing the NF-e (nota fiscal eletronica), booking shipping, sending WhatsApp notifications, and registering everything in the ERP. According to Sebrae, Brazilian SMBs spend an average of 14 hours per week on fiscal and logistics administration alone. At R$3,500/month per employee, that is R$7,000-10,500/month in labor costs for a workflow that is 95% deterministic.

The error rate is the hidden cost. Manual NF-e entry has a 3-7% rejection rate at SEFAZ (the state tax authority). Each rejected invoice requires investigation, correction, and resubmission, sometimes taking 48 hours. A single fiscal error on a R$50,000 shipment can trigger a R$5,000 fine.

The agent solution

The Complete Loop: charge, invoice, ship, notify, register, reconcile. One agent message handles the entire post-sale workflow. This is the canonical CodeSpar use case.

fulfillment-agent.ts
import { CodeSpar } from "@codespar/sdk";

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

const session = await codespar.create("fulfillment-agent", {
  preset: "brazilian",
  budgetLimit: 5000,        // R$5,000 max per session
  retryPolicy: "idempotent", // safe to retry on failure
  timeout: 120_000,          // 2 min max per step
});

const result = await session.send(`
  Process order #7721:
  1. Charge R$1,249 via Pix (Zoop)
  2. Issue NF-e for CNPJ 12.345.678/0001-90 (Sefaz SP)
  3. Ship via Correios PAC - origin CEP 01310-100, dest CEP 22041-080, 1.2kg
  4. Notify customer on WhatsApp: +55 21 99999-8888
  5. Register receivable in Omie ERP - category "online sales"
  6. Reconcile: confirm Pix settlement matches NF-e amount
`);

// result.steps contains each tool call with status, latency, and output
console.log(result.steps.map(s => `${s.tool}: ${s.status}`));

Error handling: what happens when it fails

Each step in the Complete Loop is independently retryable and idempotent. If the NF-e issuance fails (SEFAZ returns a rejection code), the agent does not proceed to shipping. Instead, it parses the SEFAZ rejection reason, corrects the XML field that caused the error (typically CFOP, NCM, or ICMS base), and resubmits. If it fails three times, it escalates to a human operator via WhatsApp with the full error context.

If the Pix charge succeeds but shipping fails (Correios API downtime, which happened 47 times in 2025 according to their status page), the agent queues a retry with exponential backoff and notifies the customer that shipping will be confirmed within 2 hours. The payment is not reversed unless shipping fails permanently.

The result

14h → 20minWeekly post-sale admin time for 200 orders/day
3-7% → 0.3%NF-e rejection rate (auto-correction on common SEFAZ errors)
R$10,500/moEstimated labor savings (2-3 FTEs on post-sale ops)
4.2 secMedian end-to-end latency for the full 6-step loop
2

WhatsApp Commerce Bot

The business problem

Brazil has 197 million WhatsApp users. According to ABCOMM, 78% of Brazilian consumers have purchased a product or service through a WhatsApp conversation in the past 12 months. Yet most WhatsApp commerce is still manual: a business owner sees a message, responds with a price, sends a Pix QR code, waits for payment confirmation, manually issues an invoice, and manually ships. For a small business doing 30 orders per day via WhatsApp, this is a full-time job that scales linearly.

The existing chatbot solutions (Take Blip, Zenvia, Weni) handle message routing but not commerce execution. They can send a canned response. They cannot charge a customer, issue a fiscal document, and book a shipment in a single conversational turn.

The agent solution

whatsapp-commerce.ts
import { CodeSpar } from "@codespar/sdk";

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

// Listen for WhatsApp messages (via Z-API webhook)
app.post("/webhook/whatsapp", async (req, res) => {
  const { from, text, messageId } = req.body;

  // Each customer gets a persistent session - conversation memory across messages
  const session = await codespar.getOrCreate(from, {
    preset: "brazilian",
    budgetLimit: 2000,
    context: {
      catalog: "https://api.mystore.com/products",
      businessCNPJ: "12.345.678/0001-90",
      shippingOrigin: "01310-100",
    },
  });

  const response = await session.send(text);

  // Agent handles the full flow conversationally:
  // "Quero 2 camisetas P" → searches catalog, quotes price + shipping
  // "Pode ser" → generates Pix QR, sends via WhatsApp
  // (customer pays) → webhook confirms, issues NF-e, books shipping
  // "Cadê meu pedido?" → checks tracking, responds with status

  await zapi.sendMessage(from, response.content);
  res.send("ok");
});

// Payment confirmation webhook - triggers fulfillment
codespar.on("payment.confirmed", async (event) => {
  const session = await codespar.get(event.data.sessionId);
  await session.send(`
    Payment confirmed for order ${event.data.orderId}.
    Execute: NF-e + shipping + customer notification.
  `);
});

Error handling: what happens when it fails

WhatsApp commerce has a unique failure mode: the customer disappears mid-conversation. They ask for a price, the agent quotes it, and the customer does not respond for 3 hours. The Z-API session expires after 24 hours of inactivity (per Meta policy). The agent handles this by: (1) saving the cart state to the session store, (2) sending a single follow-up message after 2 hours, and (3) expiring the cart after 24 hours with a polite message. No aggressive re-engagement. Brazilian consumers hate that.

If the Pix QR code expires (30 minutes by default), the agent generates a new one without the customer needing to restart the conversation. If Z-API itself is down (it had 99.7% uptime in 2025), the webhook returns a 503 and the message is queued for retry by Z-API's infrastructure.

The result

24/7Commerce availability - no business hours limitation
30→0 minAverage time from customer message to Pix QR generation
3xEstimated conversion lift (immediate response vs. 2-hour manual delay)
R$0Additional customer acquisition cost - they are already on WhatsApp
3

Cross-Border Payment Orchestrator (BR → MX via Pix + SPEI)

The business problem

LatAm cross-border payments are a disaster. A Brazilian company paying a Mexican supplier faces: (1) FX conversion with 3-6% spreads at traditional banks, (2) SWIFT fees of $25-45 per transaction, (3) 2-5 business day settlement, (4) compliance documentation requirements on both sides (Banco Central do Brasil and Banxico), and (5) no real-time visibility into where the money is. For a mid-market company making 50 cross-border payments per month, the operational cost is R$15,000-25,000/month in bank fees, FX spread losses, and staff time.

The fintech solutions (Wise, Remitly, dLocal) solve the FX and speed problems for human-initiated transfers. None of them have an API designed for autonomous agent execution. An AI agent cannot call Wise, verify its identity, initiate a transfer, and confirm settlement without human intervention at multiple steps.

The agent solution

cross-border-payment.ts
import { CodeSpar } from "@codespar/sdk";

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

const session = await codespar.create("payment-agent", {
  preset: "full-commerce",
  policies: [
    { name: "max-per-tx", type: "budget", config: { perTxLimit: 25000 } },
    { name: "daily-limit", type: "budget", config: { dailyLimit: 100000 } },
    { name: "require-approval-above", type: "approval", config: { threshold: 50000 } },
  ],
  corridors: ["BR-MX", "BR-CO", "BR-AR"], // enabled payment corridors
});

// Multi-corridor payment execution
const result = await session.send(`
  Execute the following supplier payments:

  1. Supplier: MX-Textiles SA de CV
     Amount: $2,500 USD
     Rail: SPEI (CLABE: 012180015239467835)
     FX: lock rate now, settle T+0

  2. Supplier: BR-Embalagens Ltda
     Amount: R$8,000 BRL
     Rail: Pix (CNPJ: 98.765.432/0001-10)
     Settle: immediate

  3. Supplier: CO-Logistica SAS
     Amount: COP 5,000,000
     Rail: PSE (NIT: 900123456)
     FX: lock rate now, settle T+1

  For each: confirm FX rate before execution, issue receipt, register in ERP.
`);

// result.payments contains per-payment status:
// { supplier: "MX-Textiles", status: "settled", fxRate: 17.42, fees: "$3.50" }
// { supplier: "BR-Embalagens", status: "settled", fees: "R$0" }
// { supplier: "CO-Logistica", status: "pending_t1", fxRate: 4285.30, fees: "$4.20" }

Error handling: what happens when it fails

Cross-border payments fail for three main reasons: (1) FX rate moves beyond the locked spread before execution (the agent re-quotes and requests approval if the new rate is more than 0.5% worse), (2) the receiving bank rejects the transfer (wrong CLABE, invalid NIT, etc. - the agent parses the rejection code and prompts for correction), (3) compliance hold (Banco Central flags transactions above $10,000 for additional documentation - the agent notifies the finance team and queues the payment pending document upload).

The critical design decision: every payment is idempotent. If the agent crashes after locking the FX rate but before executing the transfer, it can safely restart without double-charging. The FX lock has a 60-second TTL. If it expires, the agent re-quotes.

The result

3-6% → 0.8%FX spread reduction (aggregate rate via Stark Bank + local rails)
2-5 days → T+0/T+1Settlement time reduction
$25-45 → $3-5Per-transaction fee reduction (local rails vs. SWIFT)
R$25K/moEstimated savings for 50 cross-border payments/month
4

Fiscal Compliance Autopilot

The business problem

Brazilian fiscal compliance is a labyrinth. There are 92 different types of electronic fiscal documents across federal, state, and municipal jurisdictions. A company selling physical goods in Sao Paulo must issue NF-e (nota fiscal eletronica, governed by SEFAZ-SP). A company selling services in the same city must issue NFS-e (nota fiscal de servicos eletronica, governed by the municipal prefeitura). Sell across state borders and DIFAL (diferencial de aliquota) applies. Sell to a final consumer and you need NFC-e. Import something and you need a DI.

According to the World Bank's Doing Business report, Brazilian companies spend an average of 1,501 hours per year on tax compliance - the highest of any major economy. A Sebrae survey found that 68% of Brazilian SMBs have been fined for fiscal errors in the past 3 years, with an average fine of R$4,200.

The agent solution

fiscal-autopilot.ts
import { CodeSpar } from "@codespar/sdk";

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

// Event-driven: every completed payment triggers fiscal processing
codespar.on("payment.completed", async (event) => {
  const { amount, currency, country, customer, items, origin, destination } = event.data;

  const session = await codespar.create("fiscal-agent", {
    preset: "brazilian",
    fiscalConfig: {
      certificateId: "cert-a1-2026",   // e-CNPJ A1 certificate
      environment: "production",        // "homologation" for testing
      contingencyMode: "SCAN",          // fallback if SEFAZ is down
    },
  });

  const result = await session.send(`
    Issue the correct fiscal document:

    Amount: ${amount} ${currency}
    Customer: ${customer.name} (${customer.taxId})
    Items: ${JSON.stringify(items)}
    Origin state: ${origin.state}
    Destination state: ${destination.state}

    Rules:
    - Physical goods → NF-e (SEFAZ)
    - Services → NFS-e (Prefeitura)
    - Interstate → calculate DIFAL
    - Consumer (CPF) → NFC-e
    - B2B (CNPJ) → NF-e with full tax breakdown
    - Apply correct CFOP, NCM, ICMS, IPI, PIS, COFINS
    - If SEFAZ is offline, use SCAN contingency mode
  `);

  // result.document contains: { type: "NF-e", number: "000.123.456",
  //   accessKey: "35260612345678000190550010001234561001234560",
  //   xml: "<nfeProc>...</nfeProc>", pdf: "https://..." }
});

Error handling: what happens when it fails

SEFAZ downtime is the most common failure. In 2025, SEFAZ-SP had 23 unplanned outages totaling 67 hours. When the primary SEFAZ server is unreachable, the agent automatically switches to SCAN (Sistema de Contingencia do Ambiente Nacional), which is the federal fallback. The NF-e is issued with contingency status and automatically regularized when SEFAZ comes back online.

Tax calculation errors (wrong CFOP, wrong NCM code) are caught by SEFAZ validation before the document is authorized. The agent parses the rejection code (there are 800+ possible rejection codes in the NF-e schema), maps it to the correct field, and corrects it. For ambiguous cases (e.g., a product that could be classified under two NCM codes with different IPI rates), the agent escalates to a human with both options and their tax implications.

The result

12h → 15minMonthly NF-e issuance time for 500 invoices/month
68% → <5%Probability of receiving a fiscal fine (auto-correction)
800+SEFAZ rejection codes the agent can parse and auto-correct
99.9%NF-e issuance uptime (with SCAN contingency fallback)
5

Logistics Coordinator

The business problem

Brazilian e-commerce logistics is fragmented across 50+ carriers. Correios (the national postal service) handles 40% of e-commerce shipments but has variable pricing, frequent API issues, and different services for different routes (PAC, SEDEX, SEDEX 10, Mini Envios). Private carriers (Jadlog, Loggi, Total Express, Sequoia) each have their own APIs, pricing structures, and coverage areas. A merchant shipping 100 packages per day needs to quote across 3-5 carriers, select the optimal option for each package, generate labels in different formats, and track deliveries across different systems.

The aggregators (Melhor Envio, Frenet, Kangu) solve the quoting problem but not the execution problem. They give you prices. They do not generate labels, register shipments, or handle delivery exceptions autonomously.

The agent solution

logistics-coordinator.ts
import { CodeSpar } from "@codespar/sdk";

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

const session = await codespar.create("logistics-agent", {
  preset: "brazilian",
  logisticsConfig: {
    carriers: ["correios", "jadlog", "loggi", "total-express"],
    optimizeFor: "cost",          // "cost" | "speed" | "reliability"
    maxDeliveryDays: 7,
    insuranceAbove: 500,          // auto-insure packages above R$500
  },
});

// Batch shipping: process multiple orders at once
const result = await session.send(`
  Ship the following orders:

  Order #8001: 2.3kg, 30x20x15cm
    Origin: CEP 01310-100 (Sao Paulo, SP)
    Destination: CEP 22041-080 (Rio de Janeiro, RJ)
    Max delivery: 5 business days

  Order #8002: 0.5kg, 15x10x5cm
    Origin: CEP 01310-100 (Sao Paulo, SP)
    Destination: CEP 69020-030 (Manaus, AM)
    Max delivery: 10 business days

  Order #8003: 8.0kg, 60x40x30cm
    Origin: CEP 01310-100 (Sao Paulo, SP)
    Destination: CEP 80020-310 (Curitiba, PR)
    Max delivery: 3 business days - prioritize speed

  For each: quote all carriers, select optimal, generate label, return tracking code.
  If any carrier API is down, skip and use remaining carriers.
`);

// result.shipments: [
//   { order: "8001", carrier: "Jadlog", service: ".Package",
//     cost: "R$18.50", tracking: "JD123456789BR", eta: "3 days" },
//   { order: "8002", carrier: "Correios", service: "PAC",
//     cost: "R$32.80", tracking: "SS123456789BR", eta: "8 days" },
//   { order: "8003", carrier: "Total Express", service: "Rodoviario",
//     cost: "R$45.00", tracking: "TE789012345", eta: "2 days" },
// ]

Error handling: what happens when it fails

Carrier API failures are frequent. Correios' API had 47 documented outages in 2025. The agent handles this by: (1) maintaining a carrier health score based on recent API response times and error rates, (2) pre-filtering carriers that are currently degraded, (3) falling back to the next-cheapest carrier if the optimal one is unreachable. If all carrier APIs are down (has not happened yet, but could), the agent queues the shipment and retries every 15 minutes for up to 4 hours, then escalates.

Address validation failures are the second most common issue. Brazilian CEP codes do not always map to a deliverable address. The agent validates addresses against Correios' CEP database before quoting and flags addresses that are in restricted delivery areas (rural zones, indigenous territories, military bases) where most private carriers do not deliver.

The result

15-22%Average shipping cost reduction (multi-carrier optimization)
8min → 3secPer-order shipping time (quote + label + tracking)
100%Label generation success rate (with carrier fallback)
0Manual carrier API integrations required
6

Subscription Billing Agent with Dunning

The business problem

Subscription businesses in Brazil face a unique challenge: Pix is the preferred payment method (67% of online transactions in 2025, per Banco Central), but Pix does not natively support recurring charges. There is no “auto-debit” for Pix like there is for credit cards. Every subscription renewal requires generating a new Pix QR code, sending it to the customer, and waiting for them to pay. Involuntary churn (customer intends to pay but misses the payment) is 8-15% per month for Pix-based subscriptions, compared to 2-4% for credit card subscriptions in the US.

Dunning (recovering failed payments) is even worse. Most Brazilian SaaS companies send a single email reminder. The open rate on transactional emails in Brazil is 18%. WhatsApp message open rates are 97%. Yet most billing systems do not integrate with WhatsApp for payment recovery.

The agent solution

subscription-billing.ts
import { CodeSpar } from "@codespar/sdk";

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

// Create subscription
const session = await codespar.create("billing-agent", {
  preset: "brazilian",
  billingConfig: {
    dunningSequence: [
      { channel: "whatsapp", delay: "0h", message: "friendly_reminder" },
      { channel: "whatsapp", delay: "24h", message: "payment_link" },
      { channel: "email", delay: "48h", message: "formal_notice" },
      { channel: "whatsapp", delay: "72h", message: "last_chance" },
    ],
    gracePeriodDays: 5,
    autoSuspendAfter: 7,    // suspend access after 7 days unpaid
    autoIssueNFSe: true,    // issue NFS-e on each successful charge
  },
});

// Create a new subscription
await session.send(`
  Create monthly subscription:
  Customer: joao@email.com (CPF: 123.456.789-00, WhatsApp: +55 11 98888-7777)
  Plan: Pro - R$99/month
  Payment method: Pix (preferred) with credit card fallback
  Start date: today
  Trial: 14 days (no charge)

  On each successful charge:
  1. Issue NFS-e (service: "SaaS subscription")
  2. Send receipt via WhatsApp
  3. Register in Omie ERP as recurring revenue

  On failed payment:
  1. Execute dunning sequence (WhatsApp first, email second)
  2. Generate new Pix QR on each WhatsApp dunning message
  3. If Pix fails 3x, attempt credit card on file
  4. After grace period: suspend access, notify customer
`);

// Renewal processing (runs daily via cron)
codespar.on("subscription.renewal_due", async (event) => {
  const session = await codespar.get(event.data.sessionId);
  await session.send(`
    Process renewal for subscription ${event.data.subscriptionId}:
    Generate Pix QR for R$${event.data.amount}
    Send to customer via WhatsApp with 24h expiration
    If not paid within 24h, begin dunning sequence
  `);
});

Error handling: what happens when it fails

The primary failure mode is the customer not paying. This is not an error in the traditional sense, but it is the most expensive failure. The dunning sequence is designed to maximize recovery: WhatsApp first (97% open rate), with a fresh Pix QR code in every message (eliminating the “the QR expired” excuse). If the customer has a credit card on file and Pix fails three times, the agent silently attempts a card charge before escalating.

The technical failure mode is NFS-e issuance. Municipal NFS-e systems are notoriously unreliable (Sao Paulo's system had 31 outages in 2025). If the NFS-e fails, the agent retries for 4 hours, then issues a RPS (Recibo Provisorio de Servicos) and converts it to NFS-e when the system recovers. The customer's access is never blocked due to a fiscal system failure.

The result

8-15% → 3-5%Involuntary churn rate (WhatsApp dunning vs. email-only)
2-3xPayment recovery rate improvement (multi-channel dunning)
R$0Manual effort per subscription renewal
100%NFS-e issuance rate (with RPS fallback)
7

Multi-Country ERP Bridge

The business problem

A company operating in three LatAm countries uses three different ERPs: Omie in Brazil, Bind ERP in Mexico, and Colppy in Argentina. Each ERP has its own data model, API, authentication scheme, and fiscal requirements. A single transaction (e.g., a sale from the Brazilian entity to a Mexican customer) must be recorded in at least two ERPs with different currencies, tax treatments, and chart of accounts structures.

The consulting firms charge $150,000-300,000 for a multi-country ERP integration project that takes 6-12 months. The result is a brittle point-to-point integration that breaks every time one of the ERPs updates their API. According to Gartner, 65% of ERP integration projects exceed their budget by more than 50%.

The agent solution

erp-bridge.ts
import { CodeSpar } from "@codespar/sdk";

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

// Trigger on any payment completion across any country
codespar.on("payment.completed", async (event) => {
  const { transactionId, amount, currency, customer, method, country } = event.data;

  const session = await codespar.create("erp-agent", {
    preset: "full-commerce",
    erpConnections: {
      BR: { system: "omie", appKey: process.env.OMIE_KEY },
      MX: { system: "bind", apiKey: process.env.BIND_KEY },
      AR: { system: "colppy", token: process.env.COLPPY_TOKEN },
    },
  });

  const result = await session.send(`
    Register transaction across ERPs:

    Transaction: ${transactionId}
    Amount: ${amount} ${currency}
    Customer: ${customer.name} (${customer.taxId})
    Payment method: ${method}
    Origin country: ${country}

    Actions:
    1. Create receivable entry in the origin country ERP
    2. If cross-border: create payable entry in the destination country ERP
    3. Apply correct chart of accounts mapping:
       - BR: "1.1.03.01 - Clientes" for receivables
       - MX: "102.01 - Clientes nacionales" for receivables
       - AR: "1.1.3.01 - Deudores por ventas" for receivables
    4. Update inventory if physical goods
    5. Reconcile: verify that the sum of entries across ERPs is zero-net
  `);
});

Error handling: what happens when it fails

ERP APIs are the least reliable APIs in the LatAm stack. Omie has a rate limit of 300 requests per minute. Bind ERP returns generic 500 errors without explanatory messages. Colppy's API documentation is incomplete. The agent handles this by: (1) maintaining a queue of pending ERP entries, (2) retrying failed entries with exponential backoff, (3) detecting duplicate entries (by checking for existing entries with the same transaction ID before creating), and (4) sending a daily reconciliation report that flags any entries that failed to sync after 24 hours.

The result

$150-300K → $0ERP integration project cost (agent replaces consulting)
6-12mo → 1 dayTime to integrate a new country ERP
0Manual data entry per transaction
DailyAutomated cross-ERP reconciliation reports
8

Marketplace Split Payments (Zoop Splits)

The business problem

Brazilian marketplaces face a regulatory and operational challenge that US marketplaces do not: every transaction involving a split payment must be processed through a licensed payment facilitator (sub-acquirer), and each seller must be individually registered as a sub-merchant with full KYC (CPF/CNPJ verification, address validation, bank account verification). Zoop, Stone, and PagSeguro provide the rails, but the registration, split configuration, and reconciliation are manual.

A marketplace with 500 sellers processing 1,000 transactions per day must: (1) onboard each seller with KYC documentation, (2) configure split rules (marketplace take rate, seller payout, delivery fee allocation), (3) process each transaction with the correct split, (4) issue NF-e for the marketplace fee (service), and (5) reconcile payouts to each seller. This typically requires 4-5 people in a finance team.

The agent solution

marketplace-splits.ts
import { CodeSpar } from "@codespar/sdk";

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

// Seller onboarding
const onboardSession = await codespar.create("marketplace-agent", {
  preset: "brazilian",
  zoopConfig: {
    marketplaceId: process.env.ZOOP_MARKETPLACE_ID,
    defaultSplit: { marketplace: 15, seller: 85 },  // 15% take rate
  },
});

await onboardSession.send(`
  Onboard new seller:
  Name: Maria Silva Artesanatos
  CNPJ: 12.345.678/0001-90
  Bank: Banco do Brasil, Ag 1234, CC 56789-0
  Category: handicrafts

  Actions:
  1. Create Zoop seller account with full KYC
  2. Verify CNPJ at Receita Federal
  3. Validate bank account ownership
  4. Set split rule: 15% marketplace, 85% seller
  5. Enable Pix receiving for this seller
`);

// Transaction processing with splits
codespar.on("order.placed", async (event) => {
  const { orderId, amount, sellerId, deliveryFee } = event.data;

  const session = await codespar.create("split-agent", { preset: "brazilian" });
  await session.send(`
    Process marketplace order #${orderId}:
    Total: R$${amount} (product) + R$${deliveryFee} (delivery)

    Split:
    - Seller (${sellerId}): ${amount * 0.85} (85% of product)
    - Marketplace: ${amount * 0.15} (15% of product) + ${deliveryFee} (delivery fee)

    Payment: Pix QR code

    On payment confirmation:
    1. Execute Zoop split to seller and marketplace accounts
    2. Issue NFS-e for marketplace fee (R$${amount * 0.15})
    3. Schedule seller payout (D+2 for Pix, D+30 for credit card)
    4. Notify seller via WhatsApp: "Sale confirmed, payout in 2 days"
  `);
});

Error handling: what happens when it fails

The most dangerous failure in marketplace payments is a split execution error. If the marketplace receives R$1,000 but the split to the seller fails, the marketplace is holding the seller's money, which is a regulatory violation under Banco Central circular 3,885. The agent handles this with a two-phase commit: (1) the payment is received into an escrow account, (2) the split is executed as a separate operation. If the split fails, the money stays in escrow and the agent retries. If it fails three times, it alerts the finance team and does not release the funds to either party until resolved.

Seller onboarding failures (CNPJ not found, bank account mismatch) are caught before the seller can receive payments. The agent does not activate a seller account until all KYC checks pass.

The result

2 days → 5 minSeller onboarding time (automated KYC)
4-5 FTEs → 1Finance team size for 500-seller marketplace
100%Regulatory compliance rate (automated split reconciliation)
D+2Consistent seller payout timing (no manual delays)
9

Subscription Management with Recurring Billing and Dunning

The business problem

This is different from use case #6. Use case #6 covers Pix-native subscriptions for SMBs. This use case covers enterprise subscription management: multi-plan architectures (free, pro, enterprise), usage-based billing, mid-cycle upgrades/downgrades, prorated charges, and annual contracts with quarterly invoicing. Think of a B2B SaaS company with 2,000 customers across 5 plans with add-ons.

The US has Stripe Billing, Chargebee, and Recurly. Brazil has none of these. Vindi (the closest local equivalent) handles basic recurring billing but does not support usage-based metering, prorated plan changes, or automated dunning via WhatsApp. Most Brazilian B2B SaaS companies manage subscriptions in spreadsheets or custom-built internal tools that cost R$200,000+ to build and maintain.

The agent solution

subscription-management.ts
import { CodeSpar } from "@codespar/sdk";

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

const session = await codespar.create("subscription-agent", {
  preset: "brazilian",
  billingConfig: {
    plans: [
      { id: "free", price: 0, limits: { apiCalls: 1000, seats: 1 } },
      { id: "pro", price: 299, limits: { apiCalls: 50000, seats: 5 } },
      { id: "enterprise", price: 999, limits: { apiCalls: 500000, seats: 25 } },
    ],
    usageMetering: true,
    prorationPolicy: "day-based",  // prorate on plan change
    invoicingCycle: "monthly",
    paymentMethods: ["pix", "boleto", "credit_card"],
  },
});

// Mid-cycle plan upgrade
await session.send(`
  Process plan upgrade:
  Customer: Acme Corp (CNPJ: 11.222.333/0001-44)
  Current plan: Pro (R$299/mo, started 15 days ago)
  New plan: Enterprise (R$999/mo)

  Actions:
  1. Calculate prorated credit for remaining Pro days: R$${299 * 15/30} credit
  2. Calculate prorated Enterprise charge: R$${999 * 15/30}
  3. Net charge: R$${(999 * 15/30) - (299 * 15/30)}
  4. Generate Pix charge for net amount
  5. Update access limits immediately (50K → 500K API calls, 5 → 25 seats)
  6. Issue NFS-e for the prorated charge
  7. Update Omie ERP: change contract value, adjust MRR
  8. Notify customer on WhatsApp: upgrade confirmed, new limits active
`);

// Usage-based overage billing (runs at end of billing cycle)
codespar.on("billing.cycle_end", async (event) => {
  const session = await codespar.get(event.data.sessionId);
  await session.send(`
    Process end-of-cycle billing for ${event.data.customerId}:
    Plan: ${event.data.plan} (limit: ${event.data.limit} API calls)
    Actual usage: ${event.data.usage} API calls
    Overage: ${Math.max(0, event.data.usage - event.data.limit)} calls
    Overage rate: R$0.005 per call

    If overage > 0:
    1. Calculate overage charge
    2. Add to next invoice
    3. Send usage report to customer via email
    4. If overage > 200% of plan, suggest upgrade via WhatsApp
  `);
});

Error handling: what happens when it fails

Proration math errors are the most common issue. The agent uses day-based proration with ceiling rounding (in the customer's favor). If a dispute arises, the agent can show the exact calculation: days remaining, daily rate, credit applied. All calculations are logged with the subscription event.

Boleto payment (still used by 15% of Brazilian B2B subscriptions) has a unique failure mode: the boleto expires after 3 business days. If the customer does not pay, the agent generates a new boleto and sends it via WhatsApp. Unlike Pix, boleto settlement takes D+1 to D+3, so the agent must track settlement asynchronously and not confirm the subscription renewal until the boleto is actually paid (not just generated).

The result

R$200K+Internal billing system development cost eliminated
100%Proration accuracy (no manual calculation errors)
3 methodsPayment methods supported (Pix, boleto, credit card)
AutomaticUsage metering, overage billing, upgrade suggestions
10

AI-Powered Procurement Agent

The business problem

Mid-market Brazilian companies (R$10-100M annual revenue) spend 8-12% of revenue on procurement. The procurement process is manual: an employee identifies a need, requests quotes from 3+ suppliers (often via WhatsApp), compares prices in a spreadsheet, gets approval via email, issues a purchase order, tracks delivery, and reconciles the payment in the ERP. For a company with R$50M in revenue, that is R$4-6M in procurement spend managed by a team of 3-5 people using spreadsheets and WhatsApp.

The enterprise procurement platforms (SAP Ariba, Coupa, Jaggaer) start at $100K/year and are designed for Fortune 500 companies. There is nothing in the market for Brazilian mid-market companies that automates the full procurement cycle: supplier discovery, quote comparison, approval workflow, purchase order, delivery tracking, payment, and ERP registration.

The agent solution

procurement-agent.ts
import { CodeSpar } from "@codespar/sdk";

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

const session = await codespar.create("procurement-agent", {
  preset: "brazilian",
  procurementConfig: {
    approvalThresholds: [
      { maxAmount: 5000, approvers: [] },                    // auto-approve
      { maxAmount: 25000, approvers: ["manager@company.com"] },
      { maxAmount: 100000, approvers: ["director@company.com", "cfo@company.com"] },
    ],
    preferredSuppliers: ["supplier-a", "supplier-b", "supplier-c"],
    paymentTerms: "30 days",
  },
});

await session.send(`
  Procurement request:
  Item: 500 units of corrugated cardboard boxes (40x30x20cm)
  Requester: carlos@company.com (Operations Manager)
  Needed by: 2026-04-25
  Budget: R$15,000

  Actions:
  1. Send quote request to 3 preferred suppliers via WhatsApp/email
  2. Wait up to 48h for responses, send reminder at 24h
  3. Compare quotes: price per unit, delivery time, minimum order, payment terms
  4. Select best option (optimize for price if all deliver by deadline)
  5. Route for approval (R$15K requires manager approval)
  6. On approval: issue purchase order, send to supplier
  7. Track delivery status daily
  8. On delivery: verify quantity, generate NF-e entrada, register in ERP
  9. Schedule payment per agreed terms (boleto D+30)
`);

Error handling: what happens when it fails

Supplier non-response is the most common failure. The agent sends a quote request and waits 48 hours. If fewer than 2 suppliers respond, it expands the search to non-preferred suppliers from the Omie supplier database. If no supplier can meet the deadline, it notifies the requester with the best available option and the delivery delay.

Approval bottlenecks are the second most common issue. If the approver does not respond within 24 hours, the agent sends a WhatsApp reminder. If they do not respond within 48 hours, it escalates to the next level in the approval chain. The agent never auto-approves above the threshold, no matter how long the approver takes.

The result

5-7 days → 2 daysAverage procurement cycle time
8-15%Average cost reduction (automated multi-supplier quoting)
0Spreadsheets maintained for procurement tracking
Full auditEvery quote, approval, and payment decision is logged

The pattern across all 10 use cases

Every use case in this list follows the same pattern:

1. A deterministic workflow that humans currently execute manually. The steps are known. The decision logic is clear. The APIs exist. The only reason humans do it is because nobody has connected the pieces.

2. Multiple API integrations that are painful individually and agonizing together. Each use case involves 3-6 different APIs (payment, fiscal, shipping, messaging, ERP). Integrating any one of them takes weeks. Integrating all of them takes months. Making them work together reliably takes a team.

3. Error handling that requires domain expertise. It is not enough to call the API. You need to know what SEFAZ rejection code 539 means. You need to know that Correios PAC does not deliver to CEP ranges in certain Amazon regions. You need to know that Zoop split failures trigger regulatory obligations. This domain expertise is encoded in our MCP tools, not expected from the agent developer.

4. LatAm-specific complexity that no US infrastructure provider has solved. NF-e, Pix, CNPJ, SEFAZ, SPEI, CFDI, CEP, boleto. These are not edge cases. They are the default payment, invoicing, and logistics infrastructure for 700 million people. If your agent commerce platform does not support them, you do not support LatAm.

These are starting points. Our MCP servers and 400+ tools cover far more than these 10 scenarios. Explore the server catalog and build something we have not thought of yet.

Sources: IBGE SMB survey (2025), ABCOMM e-commerce report, Banco Central do Brasil Pix statistics, Correios annual report, Sebrae fiscal compliance study. Agent performance data from internal testing on CodeSpar Sandbox. Contact fabiano@codespar.dev for detailed benchmarks.