Skip to main content
code<spar>
Concepts

Sessions

Sessions are scoped connections to MCP servers that manage tool access, authentication, and usage tracking for AI agent commerce operations.

Sessions

A session is the core runtime primitive in CodeSpar. It represents a scoped, authenticated connection to one or more MCP servers, giving your AI agent access to commerce tools across payments, fiscal, logistics, and messaging providers in Latin America.

Sessions solve a fundamental problem: an AI agent needs to interact with dozens of commerce APIs, each with its own authentication, data format, and rate limits. Instead of wiring each provider individually, you create a session, specify which servers you need, and CodeSpar handles the rest.

Every tool call made through a session is metered for billing, scoped to your API key, and auditable through the dashboard.

Session lifecycle

Create -- Open a session specifying which servers to connect. CodeSpar authenticates with each server using your stored credentials and returns a session ID. This typically completes in 200-400ms.

Use -- List available tools, execute tool calls with session.execute(), fire off async operations with session.send(), or stream responses with session.sendStream(). All operations are scoped to the session's connected servers.

Close -- When the conversation or workflow is done, close the session to release resources. Open sessions are automatically closed after 30 minutes of inactivity. You are only billed for tool calls, not session duration.

Creating a session

With explicit servers

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

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

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

console.log(session.id);     // "ses_abc123def456"
console.log(session.status); // "active"

With curl

curl -X POST https://api.codespar.dev/v1/sessions \
  -H "Authorization: Bearer csk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{
    "servers": ["stripe", "mercadopago", "correios"]
  }'

Response:

{
  "id": "ses_abc123def456",
  "status": "active",
  "servers": [
    { "id": "stripe", "name": "Stripe", "status": "connected" },
    { "id": "mercadopago", "name": "Mercado Pago", "status": "connected" },
    { "id": "correios", "name": "Correios", "status": "connected" }
  ],
  "created_at": "2026-04-15T10:30:00Z",
  "expires_at": "2026-04-15T11:00:00Z"
}

Session options

ParameterTypeRequiredDefaultDescription
serversstring[]Yes*--List of MCP server identifiers to connect
presetstringNo--A named preset that bundles multiple servers
manageConnectionsbooleanNofalseIf true, CodeSpar manages OAuth flows for servers requiring user-level auth

*Required unless preset is specified.

Presets

Presets are named bundles of servers optimized for common commerce workflows. They reduce boilerplate and ensure you include all the servers a workflow typically needs.

// These are equivalent:
const session = await codespar.sessions.create({
  servers: ["stripe", "mercadopago", "asaas", "pagarme"],
});

const session = await codespar.sessions.create({
  preset: "payments",
});

Country-specific presets

CodeSpar provides presets tailored to regional commerce stacks:

PresetServers includedUse case
brazilianstripe, mercadopago, asaas, pagarme, correios, jadlog, nfe, nfse, twilioFull Brazilian commerce stack
mexicanstripe, mercadopago, conekta, dhl-mx, estafeta, cfdi, twilioFull Mexican commerce stack
argentinestripe, mercadopago, andreani, mercadoenvios, twilioArgentine commerce stack

Domain-specific presets

PresetServers includedUse case
paymentsstripe, mercadopago, asaas, pagarmeMulti-provider payment processing
ecommercestripe, mercadopago, correios, nfe, twilioEnd-to-end e-commerce operations
fiscalnfe, nfse, spedBrazilian fiscal compliance
logisticscorreios, jadlog, loggi, mercadoenviosMulti-carrier shipping
messagingtwilio, whatsapp, sendgridMulti-channel notifications

Presets can be combined with explicit servers. The servers field is merged with the preset's server list, and duplicates are removed automatically.

// Brazilian preset + an extra crypto server
const session = await codespar.sessions.create({
  preset: "brazilian",
  servers: ["mercadobitcoin"],
});

Executing tool calls

Sessions provide three methods for invoking tools, each suited to a different execution pattern.

session.execute() -- synchronous

Executes a tool call and waits for the result. Use this when your agent needs the response before continuing (payments, checkout links, shipping quotes).

const result = await session.execute({
  name: "codespar_pay",
  arguments: {
    method: "pix",
    amount: 9990,
    currency: "BRL",
    description: "Order #1234",
    customer_email: "maria@example.com",
  },
});

console.log(result);
// {
//   "payment_id": "pay_abc123",
//   "status": "pending",
//   "pix_code": "00020126580014br.gov.bcb.pix...",
//   "qr_code_url": "https://api.codespar.dev/qr/pay_abc123.png",
//   "expires_at": "2026-04-15T11:00:00Z"
// }

session.send() -- fire-and-forget

Sends a tool call without waiting for the result. Returns immediately after the call is queued. Use this for notifications, webhooks, and other operations where the agent does not need to inspect the response.

await session.send({
  name: "codespar_notify",
  arguments: {
    channel: "whatsapp",
    to: "+5511999999999",
    template: "order_confirmation",
    variables: { orderId: "ORD-1234", total: "R$49.90" },
  },
});
// Returns immediately -- notification is queued for delivery

session.sendStream() -- streaming

Streams partial results as they become available. Useful for long-running operations where you want to show progress to the user.

const stream = await session.sendStream({
  name: "codespar_ship",
  arguments: {
    action: "quote",
    origin_zip: "01310-100",
    destination_zip: "22041-080",
    weight_kg: 2.5,
    dimensions: { length: 30, width: 20, height: 15 },
  },
});

for await (const chunk of stream) {
  console.log(chunk); // Partial results as carriers respond
}

All three methods -- execute, send, and sendStream -- count as one tool call each for billing purposes.

The Complete Loop with session.loop()

The Complete Loop is CodeSpar's recommended pattern for multi-step agent workflows: Discover available tools, Execute the appropriate action, Confirm the result. session.loop() encapsulates this pattern.

const result = await session.loop({
  task: "Process a Pix payment of R$150 for order #5678 and send a WhatsApp confirmation",
  onStep: (step) => {
    console.log(`Step ${step.index}: ${step.tool} -> ${step.status}`);
  },
});

// Step 1: codespar_discover -> completed (found payment + notification tools)
// Step 2: codespar_pay -> completed (Pix QR code generated)
// Step 3: codespar_notify -> completed (WhatsApp message queued)

session.loop() is especially powerful when paired with an LLM. The agent can describe intent in natural language, and CodeSpar handles tool selection, sequencing, and error recovery.

session.loop() is syntactic sugar over multiple execute() calls. Each tool invocation within the loop counts as a separate tool call for billing.

MCP integration with session.mcp()

For IDE-based workflows (Claude Desktop, Cursor, Windsurf), session.mcp() exposes the session as a standard MCP server that any MCP-compatible client can connect to.

const mcpConfig = await session.mcp();

console.log(mcpConfig);
// {
//   "transport": "sse",
//   "url": "https://api.codespar.dev/mcp/ses_abc123def456",
//   "tools": [
//     { "name": "codespar_pay", "description": "..." },
//     { "name": "codespar_ship", "description": "..." },
//     ...
//   ]
// }

Add the returned URL to your MCP client configuration and all session tools become available directly in your IDE.

Listing tools

Once a session is active, retrieve all available tools:

const tools = await session.tools();

for (const tool of tools) {
  console.log(`${tool.name}: ${tool.description}`);
}
// codespar_discover: Find available commerce tools by domain
// codespar_checkout: Create a checkout session for a product or service
// codespar_pay: Process payments via Pix, boleto, card, or wallet
// ...plus server-specific tools from connected servers

session.tools() is async -- it fetches the current tool list from the connected servers. Always await it. The response includes both meta-tools and server-specific tools.

Managing connections

Some MCP servers require user-level authentication (e.g., connecting a merchant's own Stripe account via OAuth). When manageConnections is enabled, CodeSpar generates OAuth authorization URLs.

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

const connections = await session.connections();

for (const conn of connections) {
  if (conn.status === "pending") {
    console.log(`Connect ${conn.server}: ${conn.authUrl}`);
    // "Connect stripe: https://codespar.dev/connect/stripe?session=ses_..."
  }
}
curl https://api.codespar.dev/v1/sessions/ses_abc123/connections \
  -H "Authorization: Bearer csk_live_..."

Response:

{
  "connections": [
    {
      "server": "stripe",
      "status": "connected",
      "connected_at": "2026-04-15T10:31:00Z"
    },
    {
      "server": "mercadopago",
      "status": "pending",
      "authUrl": "https://codespar.dev/connect/mercadopago?session=ses_abc123"
    }
  ]
}

The user visits the authUrl, authenticates with the provider, and the connection status transitions to "connected". Tool calls to that server will then use the user's own credentials.

Session states

StateDescriptionTransitions to
pendingSession is being created; servers are connectingactive, error
activeSession is open and ready for tool callsclosed
closedSession has been closed (manually or by 30-min timeout)Terminal
errorSession creation failed (check server availability)Terminal

Closing a session

await session.close();
curl -X DELETE https://api.codespar.dev/v1/sessions/ses_abc123 \
  -H "Authorization: Bearer csk_live_..."

Sessions not explicitly closed are automatically terminated after 30 minutes of inactivity. You are billed only for tool calls made during the session, not for session duration.

Best practices

  1. Scope sessions narrowly. Only connect the servers you need. Fewer servers means faster session creation, a smaller tool list for the LLM to parse, and lower token costs in the context window.
  2. Close sessions when done. Especially in serverless environments (Vercel, AWS Lambda) where the process may be recycled before the 30-minute timeout.
  3. Reuse sessions across turns. In a multi-turn conversation, create the session once and reuse it for all turns. Do not create a new session per message.
  4. Use presets for common patterns. They reduce boilerplate and are maintained by CodeSpar as new servers are added to a category.
  5. Handle connection errors gracefully. If a server fails to connect, the session still becomes active with the remaining servers. Check session.servers to verify which connections succeeded.

Next steps