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 · updated

How CodeSpar Works

CodeSpar sits between your AI agent and every major LatAm commerce API. Instead of integrating each API individually, your agent talks to CodeSpar through a single SDK — and CodeSpar handles routing, authentication, and billing.

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 counts toward billing
  • 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 6 meta-tools that abstract all routing:

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,200 tokens (6 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/mcpMCP clientsnpm 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

CodeSpar bills per settled transaction — money movements that reach a terminal state through the runtime:

  • Open Source: free forever. MIT-licensed, self-host, no caps.
  • Orchestration: $0.10 per settled transaction + 0.5% cross-border FX. No minimum, no subscription, no per-tool-call fee.
  • Enterprise: volume-based pricing with SLAs + region pinning.

Invoicing, shipping labels, WhatsApp messages, and ERP syncs are included in the transaction price — one charge = one $0.10 tx even when it fans out to NF-e + Correios + WhatsApp. Tool calls are logged for observability but do not drive billing.

See Billing for the full model.

Next steps

Edit on GitHub

Last updated on