Skip to main content

How CodeSpar Works

Understand how CodeSpar connects your AI agent to every major LatAm commerce API through sessions, meta-tools, and MCP servers.

1 min read
View MarkdownEdit on GitHub

How CodeSpar Works

CodeSpar is the agentic operating system for money movement in Latin America. Commerce is the wedge; money movement is the platform: commerce checkout, procurement, payroll, treasury and cross-border, over the rails the region actually uses (Pix, boleto, NF-e, WhatsApp, SPEI). Instead of integrating each regional API individually, your agent talks to CodeSpar through a single SDK, and CodeSpar handles routing, authentication, and billing.

The product registry

One runtime, named by the direction money moves. Everything below in this page (sessions, meta-tools, the router) is the machinery these products share.

LayerNamesWhat they are
Sell side: you get paidGate · Meter · CollectAn x402 paywall in front of any API or MCP server (live on Base mainnet); post-paid metered pricing on it (beta); shareable payment links (early access)
Buy side: you send agents out to spendPay · Shop · WalletOutbound spend on any rail; store search and checkout; the governed multi-slot funds the agent spends from
Trust layerMandate · Receipt · Identity · Guardrails · Audit · RouterThe six primitives both sides share: signed authority, sealed proof, known parties, policy gates, the append-only record, and provider routing
Free toolsCheck · Sandbox · Catalog · Generator · SDK / CLI / Hosted MCPThe on-ramps: scan a site, test without money, browse the servers, generate an MCP server, and the three developer surfaces

The Stack

┌─────────────────────────────────────────────────┐
│  Your Agent                                     │
│  (Claude, GPT, Gemini, LangChain, CrewAI, etc.) │
└──────────────────────┬──────────────────────────┘

┌──────────────────────▼──────────────────────────┐
│  Provider Adapter                                │
│  @codespar/claude, /openai, /vercel, /mcp, etc. │
│  Converts tools to framework format              │
└──────────────────────┬──────────────────────────┘

┌──────────────────────▼──────────────────────────┐
│  @codespar/sdk                                   │
│  Session management, tool execution, billing     │
└──────────────────────┬──────────────────────────┘
                       │  HTTPS
┌──────────────────────▼──────────────────────────┐
│  CodeSpar API  (api.codespar.dev)                │
│  Auth, routing, usage tracking, rate limiting    │
└──────────────────────┬──────────────────────────┘
                       │  MCP Protocol
┌──────────────────────▼──────────────────────────┐
│  MCP Server Catalog                              │
│                                                  │
│  Payments   Stripe, Mercado Pago, Asaas, PagarMe │
│  Fiscal     NF-e, NFS-e, NFC-e, CT-e            │
│  Logistics  Correios, Jadlog, Melhor Envio       │
│  Messaging  WhatsApp, Twilio, SendGrid           │
│  Banking    Inter, Itaú, Bradesco, Nubank        │
│  ERP        Bling, Tiny, Omie, TOTVS             │
│  Crypto     Mercado Bitcoin, Foxbit              │
└─────────────────────────────────────────────────┘

Request Lifecycle

Every tool call follows the same path through the stack:

Agent decides to act

Your agent receives a user request like "Create a Pix payment for R$150" and decides to call a tool. The provider adapter converts the tool call to the SDK format.

// The agent calls codespar_pay via the adapter
const result = await session.execute("codespar_pay", {
  method: "pix",
  amount: 15000,
  currency: "BRL",
});

SDK sends to API

The SDK sends an authenticated HTTPS request to api.codespar.dev. The API validates the API key, checks rate limits, and logs the call for billing.

POST /v1/sessions/ses_abc123/execute
Authorization: Bearer csk_live_...
Content-Type: application/json

{
  "tool": "codespar_pay",
  "params": { "method": "pix", "amount": 15000, "currency": "BRL" }
}

API routes to MCP server

The API inspects the tool name and arguments, selects the best MCP server for the request (e.g., Asaas for Pix in Brazil), translates the request to the provider's format, and forwards it.

MCP server executes

The MCP server calls the provider's native API (e.g., Asaas REST API), handles retries and error normalization, and returns a structured result.

Result flows back

The result travels back through the stack: MCP server → API → SDK → adapter → agent. The agent receives a normalized ToolResult regardless of which provider handled the request.

{
  success: true,
  data: {
    payment_id: "pay_xyz789",
    pix_qr_code: "00020126...",
    pix_copy_paste: "00020126580014br.gov.bcb...",
    amount: 15000,
    status: "pending"
  },
  duration: 430,
  server: "asaas",
  tool: "codespar_pay"
}

Sessions

A session is a scoped connection to one or more MCP servers. It's the unit of work in CodeSpar.

const session = await codespar.create("user_123", {
  servers: ["stripe", "mercadopago", "correios"],
});

// Use tools...
await session.execute("codespar_pay", { ... });
await session.execute("codespar_ship", { ... });

// Clean up
await session.close();

Key properties:

  • Sessions are stateless: each tool call is independent
  • Sessions are scoped: only the servers you connect are available
  • Sessions are metered: each tool call is logged for observability; only settled money bills
  • Sessions auto-close after 30 minutes of inactivity

See Sessions for the full lifecycle reference.

Meta-Tools

Instead of exposing every raw tool from every connected server, CodeSpar provides 15 meta-tools that abstract all routing. Here are six of them:

Meta-toolWhat it doesExample
codespar_discoverFind available capabilities"What payment methods can I use?"
codespar_checkoutCreate checkout links"Create a R$99 Stripe checkout"
codespar_payProcess payments"Generate a Pix QR code for R$150"
codespar_invoiceIssue fiscal documents"Issue NF-e for order #1234"
codespar_shipQuote and create shipments"Ship 2kg from SP to RJ"
codespar_notifySend notifications"Send receipt via WhatsApp"

This reduces context window usage from ~15,000 tokens (raw tools) to ~1,800 tokens (15 meta-tools), improving agent accuracy and reducing cost.

See Tools & Meta-Tools for input schemas and response formats.

Provider Adapters

CodeSpar is framework-agnostic. Provider adapters convert Tool objects to the format each framework expects:

AdapterFrameworkInstall
@codespar/claudeAnthropic Claudenpm i @codespar/claude
@codespar/openaiOpenAI GPTnpm i @codespar/openai
@codespar/vercelVercel AI SDKnpm i @codespar/vercel
@codespar/langchainLangChain.jsnpm i @codespar/langchain
@codespar/google-genaiGoogle Gemininpm i @codespar/google-genai
@codespar/mastraMastranpm i @codespar/mastra
@codespar/crewaiCrewAInpm i @codespar/crewai
@codespar/autogenMicrosoft AutoGennpm i @codespar/autogen
@codespar/llama-indexLlamaIndex.TSnpm i @codespar/llama-index
@codespar/lettaLetta (MemGPT)npm i @codespar/letta
@codespar/camelCAMEL-AInpm i @codespar/camel
@codespar/mcpClients that spawn a local stdio process; most connect to the hosted server insteadnpm i @codespar/mcp

Every adapter exports getTools(session) to convert tools and routes execution through session.execute() so billing and audit are always tracked.

See Providers for integration guides.

Billing

One public rate card, the same for everyone, in BRL: Build, measure and think: free. Move money under mandate: 10 bps. Get paid: 1%. Never more than R$2.00 per transaction. Rails always pass through at the partner's price.

The direction of the money picks the lane:

  • Build: sandbox, catalog, SDK, CLI and Meter. Free without limit, always.
  • Move: money leaving your organization under a signed mandate. 10 bps, floor R$0.05, cap R$2.00 per transaction.
  • Get paid: money arriving in your account. 1%, no floor, cap R$2.00 per transaction.
  • Account governance: a governed account exists. R$4.90 per governed account active in the month; R$0 in a month with no outcome. Published, not yet charged.
  • Operate: outcomes that do not move money (NF-e, KYC, shipping labels, messages). Included while in preview.

The first R$1,000 settled per month, per lane, per organization, is free. A full refund within 7 days reverses the fee. No minimum, no platform fee, no rev-share.

What happenedLaneRuleCodeSpar fee
Move R$0.30 under mandateMovefloorR$0.05
Move R$100 under mandateMove10 bpsR$0.10
Move R$5,000 under mandateMovecapR$2.00
Get paid R$100Get paid1%R$1.00
Get paid R$0.50Get paid1%, no floorR$0.005
R$900 settled in the whole montheitherfree tierR$0
12 governed accounts active in the monthAccount governanceR$4.90 eachR$58.80

Tool calls are logged for observability but never drive billing. See Billing for the full model.

What is CodeSpar?

CodeSpar is the agentic operating system for money movement in Latin America. Commerce is the wedge; money movement is the platform. We provide a single SDK and a unified session model that lets your AI agents move money (commerce checkout, procurement, payroll, treasury and cross-border) and handle everything around it: process payments, issue invoices, ship packages, send notifications, and interact with ERPs, without integrating dozens of regional APIs yourself.

The products above are the doors into that runtime. Gate, Meter, and Collect are how you get paid; Pay, Shop, and Wallet are how your agents spend; Mandate, Receipt, Identity, Guardrails, Audit, and Router are the trust layer both sides share. Think of CodeSpar as the Stripe for AI agent money movement: where Stripe unified web payments behind one API, CodeSpar unifies the rails the region actually uses (Pix, boleto, Nota Fiscal, Correios, Mercado Envios, WhatsApp Business, and more) behind one SDK call that any AI agent can invoke.

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

const codespar = new CodeSpar({ apiKey: process.env.CODESPAR_API_KEY });
const session = await codespar.create("user_123", {
  servers: ["stripe", "mercadopago", "correios"],
});

const tools = await session.tools();
// 24 tools ready for your agent to call

CodeSpar is not another agent framework. It is the commerce layer that plugs into any agent framework: Claude, OpenAI, Vercel AI SDK, or any MCP-compatible client. You keep your agent architecture; CodeSpar gives it the ability to transact.

Who is CodeSpar for?

AudienceWhat CodeSpar solvesTypical side
AI engineersShip money-movement features in hours instead of weeks. No need to learn Pix settlement, NF-e XML schemas, or carrier APIs.Both
API and MCP buildersGet paid per call by agents: a Gate paywall in front of what you already run, no signup for the caller.Sell
Consumer / agent appsGive an agent a governed wallet and let it shop and pay for the user, inside caps the user signed.Buy
SaaS companiesAdd AI-powered commerce workflows to your product. Let your users' agents sell, invoice, and ship.Sell
Fintechs and ERPsExpose your services to AI agents via MCP without building your own tool layer.Both
Enterprise teamsCentralized governance, usage tracking, and billing across all agent money movement: procurement, payroll, treasury.Buy

What can you build?

Sell side, the agent (or your endpoint) collects:

Use caseHow it worksBuilt on
Paid API for agentsA Gate paywall answers 402, settles USDC per call, and proxies to your backendGate
Usage-priced inferenceThe buyer signs a ceiling; the actual cost is metered from your response and the difference refunds on-chainMeter (beta)
AI sales agent on WhatsAppAgent charges via Pix and sends the receipt in the chatcodespar_charge, codespar_notify
Automated invoicingAgent issues the fiscal document after every salecodespar_invoice
Payment reconciliationAgent monitors incoming Pix, matches to orders, triggers fulfillmentcodespar_charge, codespar_ledger
End-to-end commerceCharge, invoice, ship, notify: the full loop in one conversationcodespar_charge, codespar_invoice, codespar_ship, codespar_notify

Buy side, the agent spends:

Use caseHow it worksBuilt on
Shopping agentSearches a real store, drives the checkout, pays the store's Pix from its governed walletShop, Wallet, Pay
Contas a pagar / procurementAgent pays suppliers on schedule, every payment capped by the mandatePay, codespar_ledger
Machine spend on x402An x402-priced API answers with a quote; the agent settles it in USDC inside the per-tx capPay, Wallet
Treasury under mandateMove balance between BRL and USDC slots of one wallet, no FX guessingWallet
Bulk refundsRefund a batch of payments in parallel, partial failures handledPay

Architecture

CodeSpar sits between your AI agent and every major LatAm commerce API. Both faces converge here: a buy-side spend and a sell-side charge enter the SAME router, hit the SAME mandate and policy gates, and land in the SAME audit ledger. The side only changes which meta-tool the agent calls. The architecture has four layers:

Your Agent (Claude, GPT, Gemini, LangChain, CrewAI, or any MCP client)
    |
    v
@codespar/sdk  <-- Framework adapters: claude, openai, vercel, langchain, google-genai, mastra, crewai, autogen, llama-index, letta, camel, mcp
    |
    v
CodeSpar API (api.codespar.dev)
    |                                  Routing, auth, usage tracking, billing
    v
MCP Server Catalog
    |
    +-- Payments:    Zoop, Asaas, Pagar.me, PagSeguro, Cielo, Stone, EFI, iugu, Vindi, EBANX, Mercado Pago, Conekta, Wompi
    +-- Fiscal:      NFe.io, Focus NF-e, Facturapi, AFIP, Siigo
    +-- Logistics:   Melhor Envio, Correios, Skydropx, Andreani, Coordinadora
    +-- Messaging:   Z-API, Evolution API, Zenvia, Take Blip, RD Station
    +-- Banking:     Stark Bank, Inter, Nubank, Nequi, BCRA, Pix BCB, Open Finance, STP/SPEI
    +-- ERP:         Omie, Bling, Tiny, Conta Azul, Colppy, Alegra, Bind ERP, Belvo
    +-- E-Commerce:  VTEX, Mercado Libre, Tienda Nube
    +-- Crypto:      Mercado Bitcoin, Bitso, Circle
    +-- Protocols:   Stripe ACP, Google UCP, x402, AP2 (protocol scaffolds)
    +-- Data:        BrasilAPI

How it flows:

  1. Your agent receives a user request (e.g., "Create a R$49.90 checkout link for the Pro Plan").
  2. The adapter converts the agent's tool call into a CodeSpar SDK call.
  3. The SDK sends the request to api.codespar.dev, which authenticates, routes, and tracks usage.
  4. The API forwards the call to the appropriate MCP server (e.g., the Stripe MCP server).
  5. The MCP server executes the operation against the regional API and returns structured results.
  6. Results flow back through the stack to your agent, which presents them to the user.

You never interact with MCP servers directly. The 15 meta-tools abstract all server routing. Call codespar_charge and CodeSpar routes it to the right payment provider based on your session configuration.

The Complete Loop

Every agent interaction follows a consistent three-phase pattern we call the Complete Loop:

Discover

The agent calls codespar_discover to search the catalog for the right tool. The query is a natural-language string; results are ranked by semantic similarity and biased toward providers already connected to the session.

const result = await session.execute("codespar_discover", {
  query: "charge a buyer in BRL via Pix",
});
{
  "matches": [
    { "tool": "codespar_charge", "server": "asaas", "score": 0.91, "connected": true },
    { "tool": "codespar_charge", "server": "mercadopago", "score": 0.88, "connected": true }
  ]
}

Execute

The agent calls the appropriate meta-tool. CodeSpar routes the request to the correct MCP server based on the session's server configuration.

const result = await session.execute("codespar_charge", {
  method: "pix",
  amount: 4990,
  currency: "BRL",
  description: "Pro Plan",
});
{
  "payment_id": "pay_abc123",
  "pix_code": "00020126580014br.gov.bcb.pix...",
  "qr_code_url": "https://api.codespar.dev/qr/pay_abc123.png",
  "amount": 4990,
  "currency": "BRL",
  "status": "pending"
}

Confirm

CodeSpar returns structured results. The agent can present them to the user, chain into the next step (e.g., send the Pix code via WhatsApp), or store them for later reference.

// Chain: send the Pix code via WhatsApp
const notification = await session.execute("codespar_notify", {
  channel: "whatsapp",
  to: "+5511999887766",
  template: "pix_charge",
  variables: {
    customer_name: "Maria",
    pix_code: result.pix_code,
    amount: "R$49.90",
  },
});

The 15 Meta-Tools

Products name what you ship; meta-tools are the verbs your agent calls. They are high-level operations that abstract the underlying MCP servers: instead of calling provider-specific endpoints, your agent calls a meta-tool and CodeSpar handles the routing. They split by the side your agent plays, the same grouping you see in the sidebar.

Your agent buys: the agent spends, under a signed mandate

Meta-toolPurposeExample operation
codespar_shopSearch and buy from real stores; async checkout session to the store's payable Pix"Find dog food under R$100 and buy the best one"
codespar_walletThe agent's governed funds: balance, statement, top-up; per-currency slots"Show the wallet balance in BRL and USDC"
codespar_payOutbound spend: money leaves the wallet the agent governs"Pay R$1,500 to the supplier via Pix"
codespar_crypto_payOn-chain spend and cross-border ramps (testnet today)"Pay 25 USDC to this 0x address"
codespar_issueSpend cards bound to the same mandate governance"Issue a virtual card for the travel agent"

Your agent sells: the agent collects, as the merchant

Meta-toolPurposeExample operation
codespar_checkoutAssemble a cart and dispatch it as a charge with a hosted payment page"Create a R$99 checkout for the Pro Plan"
codespar_chargeInbound charges: the buyer pays you"Generate a Pix QR code for R$250"
codespar_invoiceFiscal documents (NFS-e default; NF-e, CFDI, Factura AR)"Issue the invoice for order #1234"
codespar_shipQuote, label, and track shipments"Ship 2kg from SP to RJ"
codespar_notifyMessages via WhatsApp, SMS, email"Send the order confirmation via WhatsApp"
codespar_kycVerify counterparties before money moves"Verify this customer before the payout"

Shared rails: both sides, no money direction

Meta-toolPurposeExample operation
codespar_ledgerDouble-entry books + the signed agentic receipts"List this month's entries for the escrow account"
codespar_discoverSemantic search across the catalog"Find tools that charge in BRL via Pix"
codespar_manage_connectionsProviders, credentials, and shopper identity"Connect WhatsApp for notifications"
codespar_get_startedThe ordered happy path for this workspace: what is connected, what to connect next, what to call first"How do I start? What can you do?"

See Tools and Meta-Tools for the full reference, including input schemas and response formats for each meta-tool.

Platform at a glance

  • Every major LatAm commerce API covered as an MCP server: payments, fiscal, logistics, messaging, banking, ERP, e-commerce, crypto, public data, and agentic commerce protocols
  • 15 meta-tools that abstract all server routing and provide a consistent interface across 85 catalog routing lines
  • Every major agent framework supported: Claude, OpenAI, Vercel AI SDK, LangChain, Google Gemini, Mastra, CrewAI, AutoGen, LlamaIndex, Letta, CAMEL-AI, plus raw MCP
  • One SDK: @codespar/sdk on npm, with a single session model for all operations
  • Free tools: Check (the Agent-Ready scan), the sandbox, the server Catalog, the MCP Generator, and the SDK, CLI, and Hosted MCP surfaces
  • Two environments: csk_test_ keys for sandbox with mock data, csk_live_ for production

Getting Started

Next steps

How CodeSpar Works | CodeSpar