Skip to main content
API Reference

SDK Reference

Complete TypeScript reference for @codespar/sdk — classes, interfaces, methods, and types.

SDK Reference

Full TypeScript reference for @codespar/sdk@0.2.0.

npm install @codespar/sdk

CodeSpar class

The entry point. Creates sessions for users.

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

const codespar = new CodeSpar({
  apiKey: "csk_live_...",     // or set CODESPAR_API_KEY env var
  baseUrl: "https://api.codespar.dev", // optional, default
});

constructor(config?: CodeSparConfig)

ParameterTypeRequiredDefaultDescription
apiKeystringYesCODESPAR_API_KEY envAPI key from dashboard
baseUrlstringNohttps://api.codespar.devAPI base URL

Throws if no API key is provided (neither in config nor env).

create(userId, config?): Promise<Session>

Creates a new session for a user.

const session = await codespar.create("user_123", {
  servers: ["stripe", "correios"],
  preset: "brazilian",
});
ParameterTypeRequiredDescription
userIdstringYesUnique user identifier
configSessionConfigNoSession configuration

SessionConfig

interface SessionConfig {
  servers?: string[];
  preset?: "brazilian" | "mexican" | "argentinian" | "colombian" | "all";
  manageConnections?: {
    waitForConnections?: boolean;
    timeout?: number; // ms, default 30000
  };
  metadata?: Record<string, string>;
}
FieldTypeDescription
serversstring[]Server IDs to connect (e.g., ["stripe", "asaas"])
presetstringCountry preset — connects all servers for that country
manageConnectionsobjectBlock until servers are connected
metadataRecordKey-value metadata attached to every tool call

Session

The main interface. Returned by codespar.create().

interface Session {
  id: string;
  userId: string;
  servers: string[];
  createdAt: Date;
  status: "active" | "closed" | "error";
  mcp: { url: string; headers: Record<string, string> };
}

tools(): Promise<Tool[]>

Returns all tools available in the session (meta-tools + server-specific tools). Caches on first call — use connections() to refresh.

const tools = await session.tools();
// [{ name: "codespar_pay", description: "...", input_schema: {...}, server: "codespar" }, ...]

findTools(intent): Promise<Tool[]>

Search tools by natural language intent. Returns tools ranked by relevance.

const tools = await session.findTools("process a Pix payment");

execute(toolName, params): Promise<ToolResult>

Execute a tool by name. Routes through the CodeSpar API for billing and audit.

const result = await session.execute("codespar_pay", {
  method: "pix",
  amount: 15000,
  currency: "BRL",
});
ParameterTypeDescription
toolNamestringTool name (e.g., codespar_pay)
paramsRecord<string, unknown>Tool input matching input_schema

loop(config): Promise<LoopResult>

Execute a multi-step workflow. Steps run in order, with access to previous results.

const result = await session.loop({
  steps: [
    { tool: "codespar_pay", params: { method: "pix", amount: 15000, currency: "BRL" } },
    { tool: "codespar_invoice", params: (prev) => ({ payment_id: prev[0].data.id }) },
  ],
  abortOnError: true,
});

send(message): Promise<SendResult>

Send a natural language message. Drives a Claude tool-use loop on the backend.

const result = await session.send("Charge R$150 via Pix and issue the NF-e");
console.log(result.message);       // Final agent response
console.log(result.tool_calls);    // Tools called during execution

sendStream(message): AsyncIterable<StreamEvent>

Stream a natural language message. Yields events as the agent runs.

for await (const event of session.sendStream("Charge R$150 via Pix")) {
  if (event.type === "assistant_text") process.stdout.write(event.content);
  if (event.type === "tool_result") console.log(event.toolCall);
  if (event.type === "done") console.log("Done:", event.result);
}

authorize(serverId, config?): Promise<AuthResult>

Initiate OAuth flow for a server that requires user-level authentication.

const auth = await session.authorize("mercado-pago");
if (!auth.connected && auth.redirectUrl) {
  // Redirect user to OAuth consent screen
  window.location.href = auth.redirectUrl;
}

connections(): Promise<ServerConnection[]>

List server connections with status and tool counts. Refreshes the internal tools cache.

const connections = await session.connections();
// [{ id: "stripe", name: "Stripe", connected: true, ... }, ...]

close(): Promise<void>

Close the session and release resources. Always call in a finally block.

try {
  // use session...
} finally {
  await session.close();
}

Types

Tool

interface Tool {
  name: string;                          // e.g., "codespar_pay"
  description: string;                   // Human-readable, shown to LLMs
  input_schema: Record<string, unknown>; // JSON Schema
  server: string;                        // Server that provides this tool
}

ToolResult

interface ToolResult {
  success: boolean;
  data: unknown;         // Tool output (varies by tool)
  error: string | null;  // Error message if failed
  duration: number;      // Execution time in ms
  server: string;        // Server that executed the tool
  tool: string;          // Tool name
  tool_call_id?: string; // Unique ID for audit
  called_at?: string;    // ISO 8601 timestamp
}

LoopConfig

interface LoopConfig {
  steps: LoopStep[];
  onStepComplete?: (step: LoopStep, result: ToolResult, index: number) => void;
  onStepError?: (step: LoopStep, error: Error, index: number) => void;
  retryPolicy?: {
    maxRetries?: number;
    backoff?: "linear" | "exponential";
    baseDelay?: number;
  };
  abortOnError?: boolean; // default: true
}

interface LoopStep {
  tool: string;
  params: Record<string, unknown> | ((prevResults: ToolResult[]) => Record<string, unknown>);
  when?: (prevResults: ToolResult[]) => boolean;
}

LoopResult

interface LoopResult {
  success: boolean;
  results: ToolResult[];
  duration: number;       // Total execution time in ms
  completedSteps: number;
  totalSteps: number;
}

SendResult

interface SendResult {
  message: string;              // Final agent response text
  tool_calls: ToolCallRecord[]; // Tools called during execution
  iterations: number;           // Model iterations
}

StreamEvent

type StreamEvent =
  | { type: "user_message"; content: string }
  | { type: "assistant_text"; content: string; iteration: number }
  | { type: "tool_use"; id: string; name: string; input: Record<string, unknown> }
  | { type: "tool_result"; toolCall: ToolCallRecord }
  | { type: "done"; result: SendResult }
  | { type: "error"; error: string; message?: string };

ToolCallRecord

interface ToolCallRecord {
  id: string;
  tool_name: string;
  server_id: string;
  status: "success" | "error";
  duration_ms: number;
  input: unknown;
  output: unknown;
  error_code: string | null;
}

ServerConnection

interface ServerConnection {
  id: string;
  name: string;
  category: string;
  country: string;
  auth_type: "oauth" | "api_key" | "cert" | "none";
  connected: boolean;
}

AuthResult

interface AuthResult {
  connected: boolean;
  redirectUrl?: string; // OAuth redirect URL
  error?: string;
}

Next steps