import { CodeSpar } from "@codespar/sdk";
const cs = new CodeSpar({ apiKey: "ak_..." });
// Create a session with the Brazilian commerce preset.
// `preset: "brazilian"` resolves to a curated set of MCP servers
// covering Pix charges (Zoop), NF-e issuance (Nuvem Fiscal), shipping
// labels (Melhor Envio), WhatsApp (Z-API), and ERP (Omie). Swap the
// preset or pass `servers: [...]` explicitly to customize.
const session = await cs.create("user_123", {
preset: "brazilian",
manageConnections: { waitForConnections: true },
// projectId: "prj_a1b2c3d4e5f6g7h8", // optional — defaults to the org's default project
});
// Natural language
const result = await session.send(
"Charge R$150 via Pix and issue the NF-e"
);
// Or execute tools directly
const charge = await session.execute("asaas/create_payment", {
customer: "cus_xxx",
billingType: "PIX",
value: 150,
});
// Don't know which tool to call? Discover by use case via the meta-tool router.
// Returns recommended + related, plus connection status so the agent knows
// whether to set anything up first.
const found = await session.discover("send a pix payment");
console.log(found.recommended);
// { server_id, tool_name, connection_status, known_pitfalls, ... }
// Surface the connect wizard when a needed server is disconnected.
// Returns a deep-link the UI renders into a Connect button — the agent
// never receives credentials directly.
const wizard = await session.connectionWizard({
action: "initiate",
server_id: found.recommended!.server_id,
});
console.log(wizard.initiate?.connect_url);
// Typed meta-tool wrappers — same wire as session.execute("codespar_charge", ...)
// but you get a typed payload back instead of the generic ToolResult envelope.
const charge = await session.charge({
amount: 150,
currency: "BRL",
method: "pix",
buyer: { name: "Cliente Demo", document: "11144477735" },
});
const label = await session.ship({
action: "label",
origin: { /* ... */ },
destination: { /* ... */ },
items: [/* ... */],
});
// Double-entry ledger (codespar_ledger) — routes to your self-hosted
// Midaz instance. Amounts in minor units; source debits must equal
// destination credits.
const posting = await session.ledger({
action: "entry",
asset: "BRL",
source: [{ account: "@external/BRL", amount: 12500 }],
destination: [{ account: "@wallet/user_1", amount: 12500 }],
});
// Async settlement — codespar_charge / codespar_pay return synchronously,
// but real settlement lands via webhook. Poll, or stream over SSE.
const settled = await session.paymentStatus(charge.tool_call_id);
await session.paymentStatusStream(charge.tool_call_id, {
onUpdate: (env) => console.log(env.status), // pending → succeeded / failed / refunded
});
// Async KYC — codespar_kyc returns the inquiry id; the buyer finishes
// the hosted flow off-platform. Poll or stream the disposition.
const v = await session.verificationStatus(inquiryToolCallId);
await session.verificationStatusStream(inquiryToolCallId, {
onUpdate: (env) => console.log(env.status), // pending → approved / rejected / review / expired
});
// Complete Loop — full commerce workflow (meta-tool driven)
import { loop } from "@codespar/sdk";
const result = await loop(session, {
steps: [
{ tool: "codespar_charge", params: { amount: 150, currency: "BRL", method: "pix", buyer: { name, document: cpf } } },
{ tool: "codespar_invoice", params: (prev) => ({ rail: "nfe", company_id, payment_id: prev[0].data.id, /* ... */ }) },
{ tool: "codespar_ship", params: { action: "label", origin, destination, items } },
{ tool: "codespar_notify", params: { recipient: phone, message: "Order received." } },
],
onStepComplete: (step, r) => console.log(`✓ ${step.tool}: ${r.duration}ms`),
});
Beyond direct canonical-tool calls, the platform registers 14
commerce-grade meta-tools that route to the best provider per
request, with failover, idempotency, and per-tenant connection config.
They split into a buy side (the agent spends), a sell side (the agent
sells), and shared infrastructure:
// Vercel AI SDK
import { getTools } from "@codespar/vercel";
const tools = getTools(session);
const result = await generateText({ model: openai("gpt-4o"), tools, prompt: "..." });
// Claude Agent SDK
import { getTools } from "@codespar/claude";
const tools = getTools(session);
// OpenAI Agents SDK
import { getTools, handleToolCall } from "@codespar/openai";
const tools = getTools(session);
// LangChain.js / LlamaIndex.TS / Mastra / CrewAI / AutoGen / CAMEL / Letta / Gemini
import { getTools } from "@codespar/langchain"; // or @codespar/llama-index, @codespar/mastra, etc.
const tools = getTools(session);
// MCP (Claude Desktop, Cursor, VS Code)
import { getMcpConfig } from "@codespar/mcp";
const { url, headers } = getMcpConfig(session);
Projects let you run independent environments — dev, staging, prod — inside a single org, each with its own connections, usage, and audit trail. Pin a client to a project with new CodeSpar({ apiKey, projectId: "prj_..." }), or override per call via cs.create(userId, { projectId: "prj_..." }). Session-level projectId wins over client-level; omit both and requests fall back to the org's default project.