Skip to main content
API Reference

SDK Reference

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

2 min read · updated

SDK Reference

@codespar/sdkv0.9.0

Full TypeScript reference for @codespar/sdk. See the migration guide when upgrading across a major.

npm install @codespar/sdk

CodeSpar class

The entry point. Creates sessions for users.

import {  } from "@codespar/sdk";

const codespar = new ({
const codespar: CodeSpar
: "csk_live_...", // or set CODESPAR_API_KEY env var : "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 .("codespar_pay", {
const result: ToolResult
: "pix", : 15000, : "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();
}

discover(query): Promise<DiscoverResult>

@codespar/sdkv0.9.0

Semantic + lexical search across the full tool catalog. Hits codespar_discover (pgvector + pg_trgm) and returns ranked tool descriptors. Use this when you want the agent to find a tool it doesn't yet have loaded into the session.

type DiscoverResult = {
  matches: Array<{
    tool_name: string;
    server_id: string;
    score: number;
    description: string;
  }>;
};

const result = await session.discover("emit a Pix QR code");
for (const match of result.matches) {
  console.log(match.tool_name, match.score);
}

Python parity: session.discover(query) (snake_case methods on AsyncSession plus a sync wrapper).

connectionWizard(serverId): Promise<ConnectionWizardResult>

@codespar/sdkv0.9.0

Returns a deep link to the dashboard wizard for the given server, or status if a connection already exists. Backed by codespar_manage_connections. Useful when an agent needs an end-user (or operator) to add credentials before continuing.

type ConnectionWizardResult = {
  status: "connected" | "pending" | "needs_setup";
  wizard_url?: string;
  connection_id?: string;
};

const wiz = await session.connectionWizard("mercado-pago");
if (wiz.status === "needs_setup") {
  console.log("Open:", wiz.wizard_url);
}

Python parity: session.connection_wizard(server_id) (AsyncSession + sync wrapper).

charge(args): Promise<ChargeResult>

@codespar/sdkv0.9.0

Typed wrapper for the codespar_charge meta-toolinbound charges (buyer pays merchant). Distinct from codespar_pay (outbound transfers). Routes Pix BRL via Asaas / Mercado Pago and card USD via Stripe.

const charge = await session.charge({
  method: "pix",
  amount: 9990,
  currency: "BRL",
  description: "Order #1234",
  customer_email: "maria@example.com",
});
console.log(charge.payment_id, charge.qr_code, charge.tool_call_id);

Charges settle asynchronously; correlate completion with session.paymentStatus() or session.paymentStatusStream().

Python parity: session.charge(args).

ship(args): Promise<ShipResult>

@codespar/sdkv0.9.0

Typed wrapper for codespar_ship. Routes through Melhor Envio with three rails selected by action:

actionBehavior
domestic-quotePrice quote for a route + parcel
domestic-labelBuy + emit a label
domestic-trackTrack an existing shipment
const quote = await session.ship({
  action: "domestic-quote",
  from_postal_code: "01310100",
  to_postal_code: "20040020",
  weight_grams: 500,
});

Python parity: session.ship(args).

paymentStatus(toolCallId): Promise<PaymentStatusResult>

@codespar/sdkv0.9.0

Polls the async settlement status for a codespar_charge or codespar_pay tool call. Wraps GET /v1/tool-calls/:id/payment-status. Returns { status: "pending" } until the provider webhook lands; on settlement, includes idempotency_key, external_reference, final_amount_minor, and settled_at.

const charge = await session.charge({ method: "pix", amount: 9990, currency: "BRL" });
let status = await session.paymentStatus(charge.tool_call_id);
while (status.status === "pending") {
  await new Promise((r) => setTimeout(r, 2000));
  status = await session.paymentStatus(charge.tool_call_id);
}

Python parity: session.payment_status(tool_call_id).

paymentStatusStream(toolCallId, options?)

@codespar/sdkv0.9.0

SSE variant of paymentStatus. Server pushes a snapshot event with the current state, then update events on each transition, then done on terminal status. The polling endpoint stays available — this is purely additive.

type StreamOptions = {
  onUpdate?: (snapshot: PaymentStatusResult) => void;
  signal?: AbortSignal;
};

const ctrl = new AbortController();
await session.paymentStatusStream(charge.tool_call_id, {
  onUpdate: (s) => console.log("status:", s.status),
  signal: ctrl.signal,
});

The server emits a heartbeat every 15s to keep proxies from dropping the connection. After a terminal state, the server holds the stream open for 5s before closing so late subscribers receive the final snapshot.

Python parity: session.payment_status_stream(tool_call_id, on_update=..., cancel_event=...).

verificationStatus(toolCallId): Promise<VerificationStatusResult>

@codespar/sdkv0.9.0

Polls the async settlement status for a codespar_kyc inquiry. Mirror of paymentStatus for KYC. Status priority is approved > rejected > review > expired > pending. Wraps GET /v1/tool-calls/:id/verification-status.

const status = await session.verificationStatus(toolCallId);
if (status.status === "approved") {
  // proceed
}

Python parity: session.verification_status(tool_call_id).

verificationStatusStream(toolCallId, options?)

@codespar/sdkv0.9.0

SSE variant of verificationStatus. Same { onUpdate, signal } shape as paymentStatusStream. The polling sibling stays available.

await session.verificationStatusStream(toolCallId, {
  onUpdate: (s) => console.log("kyc:", s.status),
});

Heartbeat every 15s; 5s grace before close after terminal state.

Python parity: session.verification_status_stream(tool_call_id, on_update=..., cancel_event=...).


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: "api_key" | "path_secret" | "oauth" | "cert" | "hmac_signed" | "none";
  connected: boolean;
}

AuthResult

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

Next steps

Edit on GitHub

Last updated on