Skip to main content

CodeSpar client

new CodeSpar(config), create(), SessionConfig, SessionConfigSchema and the cs.api property.

2 min read
View MarkdownEdit on GitHub

Client

The entry point. One CodeSpar per API key; it creates sessions and, from 0.12.0, carries the generated REST client on cs.api.

CodeSpar

Readnew CodeSpar(config?: CodeSparConfig)
PythonCodeSpar(api_key=..., base_url=..., project_id=..., timeout=...)

Constructs a client. Nothing is sent: the constructor validates the configuration and fails fast, so a misconfigured key or timeout surfaces here and not on the first call.

FieldTypeRequiredDefaultDescription
apiKeystringyes, here or in CODESPAR_API_KEYenv CODESPAR_API_KEYMust start with csk_ (csk_test_ picks the sandbox project, csk_live_ the live one)
baseUrlstringnoenv CODESPAR_BASE_URL, then https://api.codespar.devPoint it at a self-hosted runtime without changing call sites
projectIdstringnothe organization's default projectMust match ^prj_[A-Za-z0-9]{16}$; sent as x-codespar-project on every request
timeoutnumberno60000Default per-request timeout in milliseconds
Example
import {  } from "@codespar/sdk";

const  = new ({
  : "csk_test_0000",
  : "prj_0000000000000000",
});
CodeSparConfig
interface CodeSparConfig {
  apiKey?: string;
  baseUrl?: string;
  projectId?: string;
  /** Default per-request timeout in ms. Default 60000. */
  timeout?: number;
}

Throws a plain Error when no API key is found, when the key does not start with csk_, when projectId does not match the project id format, or when timeout is not a positive finite number.

Related Authentication, Projects.

create

Writecreate(userId: string, config?: SessionConfig): Promise<Session>
Pythoncs.create(user_id, config=None, /, **kwargs)

Opens a session scoped to a user. Sends POST /v1/sessions with the servers the config names (or the ones the preset expands to) and resolves to the session object. When manageConnections.waitForConnections is set, it polls connections until every server reports connected or the wait times out; an empty connection list never counts as "all connected".

ParameterTypeRequiredDescription
userIdstringyesYour identifier for the end user this session acts for
configSessionConfignoServers or preset, connection wait, metadata, project scope, test-mode mocks
Example
const  = await .("user_0000", {
  : ["asaas", "melhor-envio"],
  : { : true, : 30000 },
  : { : "ord_0000" },
});
Result: Session
// @codespar/types: what the type declares.
interface Session extends SessionBase {
  readonly id: string;
  readonly status: "active" | "closed" | "error";
  mcp?: { url: string; headers: Record<string, string> };
  // ...and the methods on the Session, Money, Status and Connections pages
}

// The object the SDK builds also has, untyped on the interface:
//   userId: string; servers: string[]; createdAt: Date

Throws a ZodError from SessionConfigSchema when the config is malformed (an unknown preset, a project id in the wrong format, a mock value that is not an object or array of objects); a CodesparApiError when the backend answers non-2xx (status, code and the parsed body on e.body) or cannot be reached (status: 0); a TimeoutError when the request exceeds the client timeout.

Related Sessions, Test mode and mocks, REST POST /v1/sessions.

SessionConfig

interface SessionConfig {
  /** Servers to connect, by id (e.g. "zoop", "nuvem-fiscal") */
  servers?: string[];
  /** "brazilian" enables the BR commerce servers */
  preset?: "brazilian" | "mexican" | "argentinian" | "colombian" | "all";
  manageConnections?: {
    /** Block until all servers are connected */
    waitForConnections?: boolean;
    /** Timeout in ms for the connection wait. Default: 30000 */
    timeout?: number;
  };
  /** Attached to every tool call in this session */
  metadata?: Record<string, string>;
  /** Overrides the client's projectId for this session */
  projectId?: string;
  /** Test-mode mocks, keyed by canonical tool name (`asaas/create_payment`) */
  mocks?: Record<string, MockValue>;
}

type MockObject = Record<string, unknown>;
type MockValue = MockObject | MockObject[];

servers wins over preset when both are given. Mock keys are forwarded verbatim: the double-underscore form (asaas__create_payment) reaches the backend unrewritten and comes back as mocks_invalid, by design. Mocks need a csk_test_ key against a test project; otherwise the backend refuses with mocks_not_permitted.

SessionConfigSchema

ReadSessionConfigSchema: z.ZodObject
not in the Python package

The zod schema create validates its config with. Exported so a caller can validate a config it received from elsewhere before opening a session, with the same rules the client applies.

import {  } from "@codespar/sdk";

const  = .({ : "brazilian" });
if (!.) .(..);

api

Readreadonly api: ApiClient
main only, not on npmnot in the Python package

The generated REST client, sharing this client's key, base URL, project scope and default timeout. Every operation of the OpenAPI document is a typed call on it; the REST client pages list them by group.

const wallet = await cs.api.get("/v1/wallets/{id}", {
  path: { id: "wlt_0000000000000000" },
});

Ships in @codespar/sdk 0.12.0. The version on npm does not have it; the example above is not compiled for that reason.

CodeSpar client | CodeSpar