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

import { Callout } from "fumadocs-ui/components/callout";
import { Step, Steps } from "fumadocs-ui/components/steps";

# 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 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:

<Steps>
<Step>
### 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.

```typescript
// The agent calls codespar_pay via the adapter
const result = await session.execute("codespar_pay", {
  method: "pix",
  amount: 15000,
  currency: "BRL",
});
```
</Step>
<Step>
### 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" }
}
```
</Step>
<Step>
### 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.
</Step>
<Step>
### 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.
</Step>
<Step>
### 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.

```typescript
{
  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"
}
```
</Step>
</Steps>

## Sessions

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

```typescript
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](/docs/concepts/sessions) for the full lifecycle reference.

## Meta-Tools

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

| Meta-tool | What it does | Example |
|-----------|-------------|---------|
| `codespar_discover` | Find available capabilities | "What payment methods can I use?" |
| `codespar_checkout` | Create checkout links | "Create a R$99 Stripe checkout" |
| `codespar_pay` | Process payments | "Generate a Pix QR code for R$150" |
| `codespar_invoice` | Issue fiscal documents | "Issue NF-e for order #1234" |
| `codespar_ship` | Quote and create shipments | "Ship 2kg from SP to RJ" |
| `codespar_notify` | Send notifications | "Send receipt via WhatsApp" |

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

See [Tools & Meta-Tools](/docs/concepts/tools) for input schemas and response formats.

## Provider Adapters

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

| Adapter | Framework | Install |
|---------|-----------|---------|
| `@codespar/claude` | Anthropic Claude | `npm i @codespar/claude` |
| `@codespar/openai` | OpenAI GPT | `npm i @codespar/openai` |
| `@codespar/vercel` | Vercel AI SDK | `npm i @codespar/vercel` |
| `@codespar/langchain` | LangChain.js | `npm i @codespar/langchain` |
| `@codespar/google-genai` | Google Gemini | `npm i @codespar/google-genai` |
| `@codespar/mastra` | Mastra | `npm i @codespar/mastra` |
| `@codespar/crewai` | CrewAI | `npm i @codespar/crewai` |
| `@codespar/autogen` | Microsoft AutoGen | `npm i @codespar/autogen` |
| `@codespar/llama-index` | LlamaIndex.TS | `npm i @codespar/llama-index` |
| `@codespar/letta` | Letta (MemGPT) | `npm i @codespar/letta` |
| `@codespar/camel` | CAMEL-AI | `npm i @codespar/camel` |
| `@codespar/mcp` | MCP clients | `npm 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](/docs/providers/claude) 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](/docs/concepts/billing) for the full model.

## Next steps

<NextStepsGrid items={[
  { label: "QUICKSTART", title: "Quickstart", description: "Make your first tool call in under 5 minutes.", href: "/docs/quickstart" },
  { label: "QUICKSTART", title: "Quickstart (Python)", description: "Same flow in sync / async Python.", href: "/docs/quickstart-python" },
  { label: "CONCEPT", title: "Sessions", description: "Lifecycle, configuration, and scoping.", href: "/docs/concepts/sessions" },
  { label: "CONCEPT", title: "Tools & Meta-Tools", description: "The 14 meta-tools reference.", href: "/docs/concepts/tools" },
  { label: "PROVIDER", title: "Claude Adapter", description: "Reference implementation for the Complete Loop.", href: "/docs/providers/claude" },
  { label: "COOKBOOK", title: "E-Commerce Checkout", description: "The architecture above, end-to-end in one cookbook.", href: "/docs/cookbooks/ecommerce-checkout" },
]} />
