Session
Every method on an open session, with its arguments and result.
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", { : "pix",
: 15000,
: "BRL",
});| Parameter | Type | Description |
|---|---|---|
toolName | string | Tool name (e.g., codespar_pay) |
params | Record<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 executionsendStream(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.10.11
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.10.11
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.10.11
Typed wrapper for the codespar_charge meta-tool — inbound 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.10.11
Typed wrapper for codespar_ship. Routes through Melhor Envio with three rails selected by action:
action | Behavior |
|---|---|
domestic-quote | Price quote for a route + parcel |
domestic-label | Buy + emit a label |
domestic-track | Track 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).
ledger(args): Promise<LedgerResult>
Typed wrapper for the codespar_ledger meta-tool — a double-entry ledger backed by the tenant's self-hosted Lerian Midaz. action picks the operation: entry posts a journal entry (source debits must equal destination credits), balance reads an account, account creates one. Amounts are in minor units; the ledger is asset-agnostic.
const entry = await session.ledger({
action: "entry",
asset: "BRL",
scale: 2,
source: [{ account: "@wallet/user_123", amount: 15000 }],
destination: [{ account: "@revenue/store", amount: 15000 }],
description: "Order #1234 settled",
});Python parity: session.ledger(args). See codespar_ledger.
issue(args): Promise<IssueResult>
Typed wrapper for the codespar_issue meta-tool — issue and control payment cards via our card-issuing partner. action picks the operation: card-virtual / card-physical issue a card, card-control freezes/unfreezes/cancels, card-get reads status.
const card = await session.issue({
action: "card-virtual",
cardholder_id: "<issuer-user-id>",
program_id: "<issuer-card-program-id>",
});Python parity: session.issue(args). See codespar_issue.
paymentStatus(toolCallId): Promise<PaymentStatusResult>
@codespar/sdkv0.10.11
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.10.11
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.10.11
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.10.11
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=...).