Dexby

SDK reference

Every option, method, and export of the Dexby TypeScript SDK.

terminal
bun add @dexby.ai/sdk
# or: npm install @dexby.ai/sdk

The SDK is ESM only and runs on your server. To use a framework provider, also install its framework; see providers.

dexby.ts
import { Dexby } from '@dexby.ai/sdk'

export const dexby = new Dexby() // reads DEXBY_API_KEY

One client per process is enough. It holds the project's API key and nothing about any end user, so every call that acts for a user names its userId.

Options

new Dexby(config) takes one optional object.

OptionTypeDefaultWhat it does
apiKeystringenv DEXBY_API_KEYProject API key. Create one in the dashboard under Configure → API keys. The constructor throws if it is empty.
baseURLstringenv DEXBY_API_URL, else Dexby Cloud (api.dexby.ai)API host. Set DEXBY_API_URL once instead of passing it.
mcpURLstringenv DEXBY_MCP_URL, else https://mcp.dexby.aiWhere MCP clients reach your MCP endpoints. Used by mcp.url(). Self-hosted setups set it to <baseURL>/v1/mcp.
providerToolProvidernew OpenAiProvider()Default format and type of session.tools(). See frameworks.
timeoutnumber60000Milliseconds each attempt of a request may take.
maxRetriesnumber2Retries after a failure that is safe to retry. See retries.
dangerouslyAllowBrowserbooleanfalseThe constructor throws BROWSER_KEY in a browser, where anyone can read the key. Set this only for a key you are willing to expose.

The client never prints the key: logging or serialising it shows no apiKey.

Calls and errors

Every method that calls the API returns a Promise and throws a DexbyError when the call fails. Each takes its parameters as one object (or an id alone), then optional request options:

execute.ts
import { Dexby, DexbyError } from '@dexby.ai/sdk'

const dexby = new Dexby()

try {
	const result = await dexby.tools.execute(
		{ toolId: 'slack_post_message', userId: 'user_123', input: { channel: 'general', text: 'Hi' } },
		{ timeout: 10_000 }
	)
	console.log(result)
} catch (error) {
	if (!(error instanceof DexbyError)) throw error
	if (error.code === 'AMBIGUOUS_CONNECTION') console.log(error.choices)
	console.warn(error.code, error.status, error.requestId)
}
DexbyError fieldTypeWhat it is
codestringWhat went wrong. Branch on it; every code is in errors.
messagestringThe API's explanation. It never contains your key, a request body, or a header.
statusnumber | undefinedThe HTTP status, when the API answered.
requestIdstring | undefinedThe call's Request-Id (req_…). Quote it to support.
retryAfternumber | undefinedSeconds the API asked you to wait, with RATE_LIMITED.
issuesunknown[] | undefinedWhat failed validation, with VALIDATION_ERROR.
choicesConnectionChoice[] | undefinedThe accounts to pick from (id, displayName, global), with AMBIGUOUS_CONNECTION.

When no answer could be read, code is one of the SDK's own: CONNECTION_ERROR (Dexby could not be reached), TIMEOUT, ABORTED (your signal), INVALID_RESPONSE (an answer this SDK version cannot read), BROWSER_KEY or WEBHOOK_INVALID (from verifyWebhook). A code this SDK version does not know arrives as the API sent it. isDexbyError(value) also recognises an error from another copy of the SDK in the same app.

A tool that ran and refused is not an error. session.call answers { ok: false, error }, which the model reads and can act on.

Request options

The last argument of every method:

OptionTypeWhat it does
signalAbortSignalCancels the call. It throws ABORTED and is never retried.
timeoutnumberMilliseconds each attempt may take, instead of the client's.
maxRetriesnumberRetries for this call, instead of the client's.
idempotencyKeystringSent as Idempotency-Key on a POST or PATCH. A repeat with the same key and request within 24 hours answers with the first result, marked Idempotent-Replayed: true, instead of acting again. While retries are on, the client makes one for each call.
headersRecord<string, string>Extra headers. They cannot replace Authorization or Idempotency-Key.

Retries

A call is retried, up to maxRetries times, after a network failure or a 408, 429, 500, 503 or 504 answer. The wait is the API's Retry-After when it asks for 60 seconds or less, otherwise an exponential backoff from half a second with jitter, at most 8 seconds.

  • GET and DELETE calls are retried.
  • POST and PATCH calls, such as tools.execute or connectLinks.create, are retried under an idempotencyKey, yours or one the client makes for the call, so a retry of a call that already acted answers with its first result instead of acting twice. With maxRetries: 0 no key is sent.
  • A 502 is never retried. Dexby answers it when the connected app failed after the call reached it, so tools.execute and tools.proxy never repeat a call the app may have acted on.

Lists

A list() method returns a page you can await, or iterate with for await for every item of every page:

lists.ts
const page = await dexby.connectors.list({ query: 'chat', limit: 20 })
console.log(page.data, page.nextCursor)
if (page.hasNextPage()) await page.getNextPage()

for await (const connection of dexby.connections.list({ userId: 'user_123' })) {
	console.log(connection.name, connection.status)
}

A page that fails throws, so iteration never returns a partial list without telling you.

Resources

MethodReturnsWhat it doesREST
connectors.list({ query?, category?, popular?, limit?, cursor? })PagePromise<ConnectorSummary>The catalog, plus the project's own MCP servers and imported APIs. limit is 1 to 500, default 100.Connectors
connectors.get(id)ConnectorDescriptorOne app with authMethods and, for built-in and imported apps, toolIds. Throws CONNECTOR_NOT_FOUND.Connectors
tools.list({ query?, connectorId?, category?, dataClassification?, view?, limit?, cursor? })PagePromise<ToolDescriptor>The project's tools. view: 'index' leaves out the schemas.Tools
tools.get(toolId)ToolDescriptorOne tool with its schemas. Throws TOOL_NOT_FOUND.Tools
tools.execute({ toolId, userId, input?, connectionId?, allowGlobalAccounts? })unknownRuns one tool as one user, outside a session. allowGlobalAccounts lets it choose a global account.Tools
tools.proxy({ connectorId, userId, endpoint, method?, query?, body?, headers?, connectionId?, allowGlobalAccounts? })unknownSends a raw request to the app's API with the user's stored credential, for endpoints no tool models.Tools
authConfigs.list({ userId?, connectorId?, limit?, cursor? })PagePromise<AuthConfig>What the project's end users can connect, oldest first. With a userId, each lists that user's connections.Auth configs
authConfigs.get(id, { userId? })AuthConfigOne auth config, as the list shows it.Auth configs
authConfigs.create({ connectorId, authMethodId?, key?, scopes?, baseUrl?, disabledActions? })AuthConfigSets up a way to connect an app. An OAuth config uses Dexby's own OAuth app; a client ID and secret of your own are set in the dashboard.Auth configs
authConfigs.update(id, { key?, authMethodId?, scopes?, baseUrl?, useManagedOAuth?, disabledActions? })AuthConfigChanges an auth config. Its method changes only while no account is connected through it.Auth configs
authConfigs.delete(id){ id, accountsRemoved }Removes an auth config and every account connected through it. Cannot be undone.Auth configs
connections.list({ userId?, connectorId?, authConfigId?, authConfig?, status?, scope?, query?, createdAfter?, limit?, cursor? })PagePromise<Connection>The project's accounts, newest first. With userId, that user's and the project's global ones (global: true); scope: 'user' leaves the global ones out.Connections
connections.get(id)ConnectionOne account, such as the one a connection.created webhook names.Connections
connections.waitFor({ userId, connectorId?, authConfig?, after?, timeout? })ConnectionWaits for the user to connect an account, as after sending a Connect link. Throws TIMEOUT, or ABORTED on your signal.Connections
connections.create({ connectorId, userId, credential, authConfig?, name? })CreatedConnectionStores a credential you already hold as one of the user's accounts. Global accounts are added in the dashboard.Connections
connections.update(id, { name }){ id, name }Renames an account.Connections
connections.rotateCredential(id, { credential, expectedRevision }){ id, revision }Replaces an account's credential, such as a token you refreshed. Throws CONFLICT when another write won.Connections
connections.setDefault(id){ id, connectorId, isDefault }Makes an account the user's default for its app.Connections
connections.delete(id){ id, erased }Removes an account, its credential, and its triggers.Connections
connectLinks.create({ userId, connectors?, authConfigs?, redirectUrl?, expiresInMinutes?, allowGlobalAccounts?, skipConsent? })ConnectLinkSingle-use link to the hosted Connect page. Its url is shown only now.Connect links
connectLinks.list({ userId?, limit?, cursor? })PagePromise<ConnectLinkSummary>The project's links, newest first, with status (active, used, expired or revoked). Never their URL.Connect links
connectLinks.revoke(id){ id, revoked }Revokes a link before it expires, as one sent to the wrong person.Connect links
users.list({ query?, connectorId?, limit?, cursor? })PagePromise<ProjectUser>The end users with at least one account, by user id.Users
users.get(userId)ProjectUserDetailOne end user: firstSeenAt, connectionCount, erasing.Users
users.erase(userId)UserErasureErases one end user from the project, in the background. Cannot be undone.Users
sessions.create({ userId, connectors?, actions?, pinned?, accounts?, allowGlobalAccounts?, policy?, ttlMinutes? })SessionOpens a session for one user. Options match the REST body.Sessions
sessions.get(id)SessionAn open session, with the user's connection state as it is now.Sessions
sessions.list({ userId?, limit?, cursor? })PagePromise<SessionSummary>The project's sessions, newest first; expired ones until they are pruned.Sessions
sessions.revoke(id){ id, revoked }Ends a session at once: its tools and MCP server answer SESSION_NOT_FOUND.Sessions
triggers.list({ userId?, connectionId?, connectorId?, limit?, cursor? })PagePromise<Trigger>The project's triggers, newest first.Triggers
triggers.get(id)TriggerDetailOne trigger with its latest events (fires).Triggers
triggers.listTypes({ connectorId?, limit?, cursor? })PagePromise<TriggerType>The apps that offer triggers, each with the events triggers.create can listen for.Triggers
triggers.create({ connectionId, event, secret?, options? })TriggerSubscribes to one event on one connection.Triggers
triggers.delete(id){ id }Removes a trigger.Triggers
mcp.url({ slug, userId })stringBuilds an MCP endpoint URL, <mcpURL>/<slug>/<userId>. Makes no request.MCP
mcp.endpoints.list({ limit?, cursor? })PagePromise<McpEndpoint>The project's MCP endpoints, by slug. Read-only: they are set up in the dashboard.MCP endpoints
mcp.endpoints.get(slug)McpEndpointOne MCP endpoint.MCP endpoints
logs.list({ status?, userId?, since?, limit?, cursor? })PagePromise<LogEntry>Logged tool runs and proxy calls, newest first: metadata only, never what a call sent or got back.Logs
logs.get(id)LogEntryOne logged call, by the Request-Id it answered with.Logs
usage.get({ from, to?, userId? })UsageRequests, tool runs, errors and bytes in a range, or one user's share.Usage

Ids are typed by their prefix (ConnectionId is `con_${string}`, and likewise AuthConfigId, TriggerId, SessionId, ConnectLinkId, UserErasureId, McpEndpointId and RequestId), so passing a trigger id where a connection id belongs fails to compile. mcp.url takes the endpoint slug you chose in Distribute → MCP endpoints.

Build your own connect screen

connectors.list browses the whole catalog. Your users can connect only the apps the project has an auth config for, so a connect screen lists those with authConfigs.list. With a userId, each config carries the user's accounts through it, so the screen can show Connect, Reconnect or Connected:

connect-screen.ts
const configs = await dexby.authConfigs.list({ userId: 'user_123' })

for (const config of configs.data) {
	const connected = config.connections?.some((account) => account.status === 'active')
	console.log(config.connector.name, config.authMethod.type, connected ? 'Connected' : 'Connect')
}

// The user picked one: send them to the hosted Connect page for that config only.
const link = await dexby.connectLinks.create({ userId: 'user_123', authConfigs: ['slack'] })
console.log(link.url)

Each AuthConfig has id, key, name, connector (id, name, category, logo), authMethod (id, type, name; type is none for an app that needs no sign-in) and scopes. Each connections item has id, name, status (active, reauth_required or revoked), isDefault and global. No OAuth client or credential is ever returned.

Session

sessions.create() and sessions.get() resolve to a Session.

MemberTypeWhat it is
idSessionIdSession id.
userIdstringThe end user.
mcpUrlstringThe session as an MCP server. See MCP.
stateSessionStateScope, policy, expiry, and each connector's connection status as last read.
refresh(options?)Promise<Session>Reads the session again, as after the user connected an app, and updates state.
definitions({ format? }, options?)Promise<SessionTool[]>Tool definitions, 'json-schema' (default) or 'openai-strict'.
call(name, args, options?)Promise<ToolOutcome>Runs one session tool with the model's arguments.
tools({ provider? }, options?)Promise<T>The tools in the client's provider format, or provider's for this call, each calling back into this session.
handleToolCalls(response, { provider? }, options?)Promise<R>Runs the tool calls in a model API response through this session and answers with the messages to send back. See providers.

A ToolOutcome is { ok: true, result } or { ok: false, error }. The second is a refusal the model reads and acts on, not a DexbyError. A tool from session.tools() whose call fails also hands the model { ok: false, error }. See Sessions.

Providers

A provider turns session tools into one framework's tool type. Pass it as provider. Framework providers need that framework installed next to the SDK (an optional peer dependency). Model API providers return plain definitions without a framework dependency, and run the model's tool calls for you. Install the model client package if your application calls its API directly.

ProviderFrameworkInstall alongside
OpenAiProviderOpenAI Chat Completions (default)nothing
OpenAiResponsesProviderOpenAI Responses APInothing
OpenAiAgentsProviderOpenAI Agents SDK@openai/agents (^0.21.0)
AnthropicProviderAnthropic Messages APInothing
GeminiProviderGoogle Gemininothing
GoogleAdkProviderGoogle Agent Development Kit@google/adk (^2.1.0)
BedrockProviderAmazon Bedrock Conversenothing
AiSdkProviderVercel AI SDKai (5, 6, or 7)
MastraProviderMastra@mastra/core (^1.71.0)
LangChainProviderLangChain@langchain/core (^1.2.13)
LlamaIndexProviderLlamaIndex@llamaindex/core (^0.6.23)
GenkitProviderGenkitgenkit (^1.42.0)
StrandsProviderStrands Agents@strands-agents/sdk (^1.19.0)

Snippets for each are in frameworks.

The model API providers also run a response's tool calls. session.handleToolCalls(response) reads the calls, runs each through session.call, and answers with the messages to append before the next model request: tool messages for Chat Completions, function_call_output items for the Responses API, one tool_result user message for Anthropic, one functionResponse content for Gemini and one toolResult user message for Bedrock. A refusal reaches the model as its result.

anthropic-loop.ts
import Anthropic from '@anthropic-ai/sdk'
import { Dexby } from '@dexby.ai/sdk'
import { AnthropicProvider } from '@dexby.ai/sdk/providers/anthropic'

const anthropic = new Anthropic()
const provider = new AnthropicProvider()
const dexby = new Dexby({ provider })
const session = await dexby.sessions.create({ userId: 'user_123' })
const tools = await session.tools()

const messages: Anthropic.MessageParam[] = [{ role: 'user', content: 'Post hi in #general' }]
for (;;) {
	const response = await anthropic.messages.create({
		model: 'claude-sonnet-4-5',
		max_tokens: 1024,
		tools,
		messages
	})
	messages.push({ role: 'assistant', content: response.content })
	// Naming the provider types the messages it answers with.
	const results = await session.handleToolCalls(response, { provider })
	if (results.length === 0) break
	messages.push(...results)
}

A ToolExecutor, which framework providers call, takes (name, input, { signal }).

Webhooks

verifyWebhook from @dexby.ai/sdk/webhooks checks that a delivery came from Dexby and answers with its typed event. It loads no client, so a webhook receiver stays small.

webhook.ts
import { verifyWebhook } from '@dexby.ai/sdk/webhooks'

export async function POST(request: Request) {
	const event = await verifyWebhook({ request, secret: process.env.DEXBY_WEBHOOK_SECRET ?? '' })
	if (event.type === 'connection.created') console.log(event.data.connectionId, event.data.userId)
	return new Response(null, { status: 204 })
}
ParameterTypeWhat it is
requestRequestThe delivery, as a Fetch Request. Its body is read from a clone.
body, headersstring | Uint8Array, Headers | Record<string, string | string[]>Instead of request: the raw body exactly as received, and the headers, such as Node's req.headers.
secretstring | string[]The endpoint's whsec_… signing secret. While a rotated secret overlaps, either secret verifies; pass both while you switch.
toleranceSecondsnumberHow old or new a delivery may be. Default 300.

It throws DexbyError with WEBHOOK_INVALID for a missing or wrong signature, a timestamp outside the tolerance, or a body that is not an event this SDK version knows. The event is { id, type, timestamp, data }; id is the delivery's webhook-id, the same on every retry, so you can process each delivery once. Any Standard Webhooks library verifies the same deliveries; see triggers.

Exports

PathExports
@dexby.ai/sdkDexby, DexbyError, isDexbyError, Session, OpenAiProvider, and types (Page, PagePromise, RequestOptions, ids, ...)
@dexby.ai/sdk/contractsdexbyConfigSchema, toolInputSchema, types ToolProvider, ToolExecutor, ToolCallHandler, DexbyErrorCode, WebhookEvent, ids
@dexby.ai/sdk/webhooksverifyWebhook, types WebhookEvent, WebhookEventType, VerifyWebhookParams
@dexby.ai/sdk/providers/openaiOpenAiProvider
@dexby.ai/sdk/providers/openai-responsesOpenAiResponsesProvider
@dexby.ai/sdk/providers/openai-agentsOpenAiAgentsProvider
@dexby.ai/sdk/providers/anthropicAnthropicProvider
@dexby.ai/sdk/providers/geminiGeminiProvider
@dexby.ai/sdk/providers/google-adkGoogleAdkProvider
@dexby.ai/sdk/providers/bedrockBedrockProvider
@dexby.ai/sdk/providers/ai-sdkAiSdkProvider
@dexby.ai/sdk/providers/mastraMastraProvider
@dexby.ai/sdk/providers/langchainLangChainProvider
@dexby.ai/sdk/providers/llamaindexLlamaIndexProvider
@dexby.ai/sdk/providers/genkitGenkitProvider
@dexby.ai/sdk/providers/strandsStrandsProvider

Upgrading from 0.10

0.11 is a clean break: every call returns a Promise and throws a DexbyError, methods live on resources, and the client has no default user.

0.100.11
ResultAsync results, SdkErrorPromise results; failures throw DexbyError
new Dexby({ userId })removed: pass userId to each call
createSession(options)sessions.create({ userId, ...options })
execute(options)tools.execute({ userId, ...options })
createConnectLink(options)connectLinks.create({ userId, ...options })
listAuthConfigs(options)authConfigs.list(options), a page
listConnections(options)connections.list({ userId }), a page
deleteConnection(id, signal)connections.delete(id, { signal })
eraseUser(userId, signal)users.erase(userId, { signal })
createTrigger / listTriggers / deleteTriggertriggers.create / triggers.list / triggers.delete
mcpUrl(slug, userId?)mcp.url({ slug, userId })
searchTools(query), every pagetools.list({ query }), a page; for await for all
searchConnectors / searchConnectorsPageconnectors.list(params)
getConnector(id), undefined when missingconnectors.get(id), throws CONNECTOR_NOT_FOUND
session.definitions(format, signal)session.definitions({ format }, { signal })
session.call(name, args, signal)session.call(name, args, { signal })
session.tools(signal)session.tools({ provider? }, { signal })
dexby.apiKey, dexby.userIdremoved
UNKNOWN, CANCELLED codesthe API's own code as sent; ABORTED

On this page