Skip to main content
Providers

AutoGen

Use @codespar/autogen to give Microsoft AutoGen agents commerce capabilities in Latin America.

AutoGen Adapter

The @codespar/autogen adapter converts CodeSpar session tools into Microsoft AutoGen's function tool format. Each tool includes a callable that routes execution through the CodeSpar session for billing and audit. Use it to give your AutoGen multi-agent conversations access to payments, invoicing, and shipping in Latin America.

Installation

npm install @codespar/sdk @codespar/autogen
pnpm add @codespar/sdk @codespar/autogen
yarn add @codespar/sdk @codespar/autogen

@codespar/autogen has a peer dependency on @codespar/sdk@^0.2.0. Make sure it is installed.

API Reference

getTools(session): Promise<AutoGenFunctionTool[]>

Fetches all tools from the session and converts them to AutoGen's function tool format. Each tool has type: "function", a function object with name, description, and parameters, plus a callable for execution.

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

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

const tools = await getTools(session);
console.log(JSON.stringify(tools[0], null, 2));
Output: AutoGenFunctionTool
{
  "type": "function",
  "function": {
    "name": "codespar_checkout",
    "description": "Create a checkout session for a product or service",
    "parameters": {
      "type": "object",
      "properties": {
        "provider": { "type": "string" },
        "amount": { "type": "number" },
        "currency": { "type": "string" }
      },
      "required": ["provider", "amount", "currency"]
    }
  }
}

toAutoGenTool(tool, session): AutoGenFunctionTool

Converts a single CodeSpar tool to AutoGen format with a bound callable.

import { toAutoGenTool } from "@codespar/autogen";

const allTools = await session.tools();
const paymentTools = allTools
  .filter((t) => t.name.includes("pay"))
  .map((t) => toAutoGenTool(t, session));

handleToolCall(session, toolName, args): Promise<ToolResult>

Convenience executor that routes a tool call through the CodeSpar session.

Full agent loop

This is a complete example of an AutoGen multi-agent conversation with CodeSpar tools:

autogen-agent.ts
import { CodeSpar } from "@codespar/sdk";
import { getTools } from "@codespar/autogen";

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

async function run(userMessage: string) {
  // 1. Create a session
  const session = await codespar.sessions.create({
    servers: ["stripe", "asaas", "correios"],
  });

  // 2. Get tools in AutoGen format
  const tools = await getTools(session);

  // 3. Create a tool registry for easy lookup
  const toolRegistry = new Map(
    tools.map((t) => [t.function.name, t])
  );

  // 4. Simulate an agent loop (adapt to your AutoGen setup)
  const toolName = "codespar_checkout";
  const tool = toolRegistry.get(toolName);

  if (tool) {
    const result = await tool.callable({
      provider: "stripe",
      amount: 25000,
      currency: "BRL",
      description: "Order #1234",
    });
    console.log("Tool result:", result);
  }

  // 5. Clean up
  await session.close();
}

await run("Process payment of R$250 via Pix");

Handling parallel tool calls

Execute multiple tool callables in parallel when the agent requests them:

const toolCalls = [
  { name: "codespar_checkout", args: { provider: "stripe", amount: 4990, currency: "BRL" } },
  { name: "codespar_notify", args: { channel: "email", to: "customer@example.com" } },
];

const results = await Promise.all(
  toolCalls.map(async (tc) => {
    const tool = toolRegistry.get(tc.name);
    if (!tool) throw new Error(`Unknown tool: ${tc.name}`);
    return { name: tc.name, result: await tool.callable(tc.args) };
  })
);

Streaming

AutoGen supports streaming conversations. Use the callable in your tool execution handler:

autogen-streaming.ts
import { CodeSpar } from "@codespar/sdk";
import { getTools } from "@codespar/autogen";

const codespar = new CodeSpar({ apiKey: process.env.CODESPAR_API_KEY });
const session = await codespar.sessions.create({ servers: ["stripe"] });
const tools = await getTools(session);

// Register tools with your AutoGen agent's tool executor
async function executeToolCall(name: string, args: Record<string, unknown>) {
  const tool = tools.find((t) => t.function.name === name);
  if (!tool) return JSON.stringify({ error: `Unknown tool: ${name}` });
  return tool.callable(args);
}

Error handling

Wrap callable invocations in try-catch:

async function safeExecute(tool: AutoGenFunctionTool, args: Record<string, unknown>) {
  try {
    return await tool.callable(args);
  } catch (error) {
    return JSON.stringify({
      error: error instanceof Error ? error.message : "Tool call failed",
      tool_name: tool.function.name,
    });
  }
}

Returning errors as JSON strings lets the AutoGen agent reason about failures and decide whether to retry or try a different approach.

Best practices

  1. Always close sessions. Use try/finally to ensure session.close() runs.

  2. Scope servers narrowly. Only connect the MCP servers your agents need.

  3. Build a tool registry. Use a Map keyed by tool name for O(1) lookups in the tool execution handler.

  4. Set conversation limits. Configure max_consecutive_auto_reply to prevent infinite agent loops.

  5. Return errors as strings. Let agents reason about failures instead of crashing the conversation.

  6. Use typed tool calls. The AutoGenFunctionTool interface ensures type safety in your tool execution handler.

Next steps