TypeScript SDK
@truto/truto-ts-sdk is a TypeScript/JavaScript library to interact with the Truto API. It wraps the Unified and Proxy APIs and the core Admin API endpoints of the Truto API Reference; Admin resources lists which. For anything else, call await trutoApi.apiClient.request('/tenant', { method: 'GET' }); the path must start with / (see Calling any endpoint).
Package: npmjs.com/package/@truto/truto-ts-sdk. Source: github.com/trutohq/truto-ts-sdk. The methods on this page are in version 2.1.0.
Requirements
Node.js 20 or later (the library uses fetch). The CommonJS require form needs Node.js 20.19+ or 22.12+; on older versions use the ESM import.
Installation
npm install @truto/truto-ts-sdkor via yarn:
yarn add @truto/truto-ts-sdkQuick start
Create an API token, then import the client. With ESM:
import TrutoApi from '@truto/truto-ts-sdk'With CommonJS (Node.js 20.19+ or 22.12+):
const { default: TrutoApi } = require('@truto/truto-ts-sdk');Create a client and call the APIs:
const trutoApi = new TrutoApi({
token: process.env.TRUTO_API_TOKEN,
})// Fetch all installed integrations
const installedIntegrations = trutoApi.environmentIntegration.list()
for await (const installedIntegration of installedIntegrations) {
console.log(installedIntegration)
}
// Fetch integrated accounts for a tenant
const integratedAccounts = trutoApi.integratedAccount.list({
tenant_id: 'acme-1',
})
console.log(await integratedAccounts.toArray()) // To fetch all
// Install an integration to the environment the API token is associated with
await trutoApi.integration.install('32b122db-ad24-400f-8ee7-0be21edc12ef')
// Make a request to the unified API
const unifiedApiCursor = trutoApi.unifiedApi.list({
unified_model: 'accounting',
resource: 'accounts',
integrated_account_id: '766cc1ee-6637-4aa1-a73e-a0c89ccc867c',
created_at: '2023-05-01T00:00:00.000Z',
})
for await (const unifiedApiResource of unifiedApiCursor) {
console.log(unifiedApiResource)
}
const unifiedApiResource = await trutoApi.unifiedApi.get('1', {
unified_model: 'accounting',
resource: 'accounts',
integrated_account_id: '766cc1ee-6637-4aa1-a73e-a0c89ccc867c',
})
console.log(unifiedApiResource)How the client works
- One client.
new TrutoApi({ token, baseUrl })takes your API token and an optionalbaseUrl, which defaults tohttps://api.truto.one. - Resources. Each Admin API resource is a property of the client, such as
trutoApi.integratedAccountortrutoApi.syncJob(see Admin resources). Most exposelist,get,create,update(PATCH), anddelete. - Query parameters are a plain object, such as
list({ tenant_id: 'acme-1' }). Nested objects and arrays are encoded the way the API expects (filter[status]=open,ids[0]=a). - Request options last. Unified and Proxy API methods take an options object as their last argument, for retries, the timeout, and extra headers (see Retries and timeouts). Admin resource methods take no options object and use the defaults.
- Errors. A non-2xx response throws a
TrutoError(see Errors).
Errors
import TrutoApi, { TrutoError, TrutoTimeoutError } from '@truto/truto-ts-sdk'
try {
await trutoApi.integratedAccount.get('766cc1ee-6637-4aa1-a73e-a0c89ccc867c')
} catch (err) {
if (err instanceof TrutoTimeoutError) {
// the attempt ran past its timeout
} else if (err instanceof TrutoError) {
console.log(err.statusCode, err.data)
}
}TrutoError has statusCode, statusText, response, and data, the parsed response body. Its message is the status text, so read Truto's message, truto_error_code, and truto_error_insight from err.data. TrutoTimeoutError extends TrutoError, with status code 408. A network failure is thrown as fetch throws it, not as a TrutoError.
A 401 is not always your API token. With truto_is_remote_error: true in the body, the provider refused the integrated account's credentials; with truto_error_code: integrated_account_needs_reauth, the account is stale. Both need the account reconnected, not a new token. See Errors.
Retries and timeouts
The TypeScript SDK retries failed requests for you. Keep the rate limits in mind: per API token, 100 requests per second and 500 per 10 seconds; per integrated account, 50 requests per 10 seconds.
Unified and Proxy API methods take these options as their last argument:
const result = await trutoApi.unifiedApi.list({
unified_model: 'accounting',
resource: 'accounts',
integrated_account_id: '766cc1ee-6637-4aa1-a73e-a0c89ccc867c',
}, {
retryStatusCodes: [429, 503],
defaultRetryAfter: 5,
maxRetries: 5,
timeout: 60,
onRetry: (retryCount, statusCode) => {
console.log(`Retry attempt ${retryCount} due to status code ${statusCode}`);
},
onRateLimited: (retryAfter, retryCount) => {
console.log(`Rate limited, waiting ${retryAfter}s before retry ${retryCount + 1}`);
}
}).toArray();| Option | Default | Description |
|---|---|---|
noRetry |
false |
Disable retries for this request. When true, the other retry options have no effect |
retryStatusCodes |
[408, 409, 425, 429, 502, 503, 504] |
Extra HTTP status codes to retry on. They are added to the defaults, so the defaults are always retried |
defaultRetryAfter |
10 |
Seconds to wait before retrying a 429 response that has no Retry-After header. Other retryable status codes are retried immediately |
maxRetries |
3 |
Maximum number of attempts, the first one included (3 means up to 2 retries) |
timeout |
30 |
Timeout in seconds for each attempt. A timed-out attempt throws TrutoTimeoutError and is not retried |
headers |
— | Extra request headers, such as Idempotency-Key |
onRetry |
— | Called after each failed retryable attempt, including the last one |
onRateLimited |
— | Callback notified on 429 responses |
Numeric options set to 0 fall back to their defaults.
409is retried by default, unlike the retry strategy advice; passnoRetry: truewhere a conflict is expected.- Network errors are not retried.
- A timeout throws
TrutoTimeoutError(status408), but the request is not aborted: it keeps running in the background. - A
429on the last attempt still waits forRetry-Afterbefore the error is thrown.
The request body is sent again on every attempt, and a 502 or 504 can arrive after the provider has already applied a write. Send an Idempotency-Key header on Unified and Proxy writes (create, update, and custom methods). For 24 hours, a retry with the same key, path, and integrated account that is sent after the first response gets that stored response, even a 502, instead of calling the provider again. Use a new key after you fix a 4xx. Delete calls and the Custom API don't support it; pass noRetry: true there.
await trutoApi.unifiedApi.create(
{ first_name: 'Ada' },
{
unified_model: 'crm',
resource: 'contacts',
integrated_account_id: '766cc1ee-6637-4aa1-a73e-a0c89ccc867c',
},
{ headers: { 'Idempotency-Key': 'contact-ada-0001' } } // one key per write
)Pagination
list methods return a Cursor that follows next_cursor for you. Nothing is fetched until you read from it.
Iterate it with for await:
const accounts = trutoApi.integratedAccount.list({ tenant_id: 'acme-1' })
for await (const account of accounts) {
console.log(account.id)
}Collect every page with toArray(), or take the first item with first():
const all = await trutoApi.integratedAccount.list({ tenant_id: 'acme-1' }).toArray()
const first = await trutoApi.integratedAccount.list({ tenant_id: 'acme-1' }).first() // undefined if there are noneOr fetch one page at a time with next(), which returns { items, nextCursor }. Stop when nextCursor is empty: calling next() after the last page starts again from the first page.
const cursor = trutoApi.integratedAccount.list({ tenant_id: 'acme-1', limit: 50 })
let page
do {
page = await cursor.next()
console.log(page.items.length)
} while (page.nextCursor)Files
The SDK supports file uploads using FormData:
const formData = new FormData();
formData.append('file', fileObject);
formData.append('name', 'example.pdf');
await trutoApi.unifiedApi.create(formData, {
unified_model: 'file-storage',
resource: 'drive-items',
integrated_account_id: '766cc1ee-6637-4aa1-a73e-a0c89ccc867c',
});
// With body passthrough (sends FormData directly to integration)
await trutoApi.unifiedApi.create(formData, {
unified_model: 'file-storage',
resource: 'drive-items',
integrated_account_id: '766cc1ee-6637-4aa1-a73e-a0c89ccc867c',
truto_body_passthrough: true,
});A response that isn't JSON resolves to a Blob instead of an object.
Unified API
Accessible via trutoApi.unifiedApi. Each call takes an object naming the unified model, the resource, and the integrated account, plus any query parameters. Each unified model has its own API reference, for example CRM. Query parameters every Unified call accepts: Querying.
const contacts = {
unified_model: 'crm',
resource: 'contacts',
integrated_account_id: '766cc1ee-6637-4aa1-a73e-a0c89ccc867c',
}
const all = await trutoApi.unifiedApi.list({ ...contacts, limit: 50 }).toArray()
const contact = await trutoApi.unifiedApi.get('123', contacts)
const created = await trutoApi.unifiedApi.create({ first_name: 'Ada' }, contacts)
await trutoApi.unifiedApi.update('123', { first_name: 'Grace' }, contacts)
await trutoApi.unifiedApi.delete('123', contacts)
// Custom methods: POST /unified/{model}/{resource}/{method}
const results = await trutoApi.unifiedApi.customMethod('search', { query: 'acme' }, contacts)
// Mapping metadata for one method on the account's integration
const meta = await trutoApi.unifiedApi.meta('list', contacts)| Method | Endpoint |
|---|---|
list(query, options?) |
GET /unified/{model}/{resource} |
get(id, query, options?) |
GET /unified/{model}/{resource}/{id} |
create(body, query, options?) |
POST /unified/{model}/{resource} |
update(id, body, query, options?) |
PATCH /unified/{model}/{resource}/{id} |
delete(id, query, options?) |
DELETE /unified/{model}/{resource}/{id} |
customMethod(method, body, query, options?) |
POST /unified/{model}/{resource}/{method} |
meta(method, query, options?) |
GET /unified/{model}/{resource}/meta/{method} |
meta returns the mapping metadata (schema and supported parameters) of one unified method, for the integrated account's integration.
Proxy API
Accessible via trutoApi.proxyApi. Calls go to the integration's own API through Truto, with resource names as defined on the integration.
const tickets = {
resource: 'tickets',
integrated_account_id: '766cc1ee-6637-4aa1-a73e-a0c89ccc867c',
}
const all = await trutoApi.proxyApi.list(tickets).toArray()
const ticket = await trutoApi.proxyApi.get('123', tickets)
await trutoApi.proxyApi.create({ subject: 'Help' }, tickets)
await trutoApi.proxyApi.update('123', { status: 'closed' }, tickets)
await trutoApi.proxyApi.delete('123', tickets)
await trutoApi.proxyApi.customMethod('merge', { ids: ['1', '2'] }, tickets)| Method | Endpoint |
|---|---|
list(query, options?) |
GET /proxy/{resource} |
get(id, query, options?) |
GET /proxy/{resource}/{id} |
create(body, query, options?) |
POST /proxy/{resource} |
update(id, body, query, options?) |
PATCH /proxy/{resource}/{id} |
delete(id, query, options?) |
DELETE /proxy/{resource}/{id} |
customMethod(method, body, query, options?) |
POST /proxy/{resource}/{method} |
Custom API
The Custom API sends a request to any path of the integration's API, with the integrated account's credentials, at /custom/{path}. In version 2.1.0, trutoApi.customApi doesn't reach the API, so call it with apiClient.request:
const ia = '766cc1ee-6637-4aa1-a73e-a0c89ccc867c'
const result = await trutoApi.apiClient.request(
`/custom/my/custom/path?integrated_account_id=${ia}`,
{ method: 'GET' }
)
await trutoApi.apiClient.request(`/custom/my/custom/path?integrated_account_id=${ia}`, {
method: 'POST',
body: { key: 'value' },
})MCP
Talks to an integrated account's MCP server, using the token from Create MCP server. See MCP servers. In version 2.1.0, trutoApi.mcp doesn't reach the API, so send the JSON-RPC message with apiClient.request:
const mcpToken = 'your-mcp-token'
const tools = await trutoApi.apiClient.request(`/mcp/${mcpToken}`, {
method: 'POST',
body: { jsonrpc: '2.0', id: 1, method: 'tools/list' },
})
const result = await trutoApi.apiClient.request(`/mcp/${mcpToken}`, {
method: 'POST',
body: {
jsonrpc: '2.0',
id: 2,
method: 'tools/call',
// a name returned by tools/list
params: { name: 'list_all_zendesk_tickets', arguments: { status: 'open' } },
},
})Admin resources
Each resource is a property of the client. list takes its query parameters as its only argument; get, update, and delete take the ID first.
| Property | Methods | Endpoint | Reference |
|---|---|---|---|
integratedAccount |
list, get, update, delete, tools |
/integrated-account, /integrated-account/{id} |
Integrated accounts |
integration |
list, get, create, update, delete, install |
/integration, /integration/{id} |
Integrations |
environmentIntegration |
list, get, update, delete |
/environment-integration, /environment-integration/{id} |
Environment integrations |
unifiedModel |
list, get, create, update, delete, install |
/unified-model, /unified-model/{id} |
Unified models |
environmentUnifiedModel |
list, get, create, delete |
/environment-unified-model, /environment-unified-model/{id} |
Environment unified models |
linkToken |
createForNewIntegration, createForExistingIntegratedAccount |
POST /link-token |
Link tokens |
syncJob |
list, get, create, update, delete |
/sync-job, /sync-job/{id} |
Sync jobs |
syncJobRun |
list, get, create, update, delete |
/sync-job-run, /sync-job-run/{id} |
Sync job runs |
syncJobCronTrigger |
list, get, create, update, delete |
/sync-job-cron-trigger, /sync-job-cron-trigger/{id} |
Sync job cron triggers |
webhook |
list, get, create, update, delete |
/webhook, /webhook/{id} |
Webhooks |
workflow |
list, get, create, update, delete |
/workflow, /workflow/{id} |
Workflows |
workflowRun |
list, get, delete |
/workflow-run, /workflow-run/{id} |
Workflow runs |
datastore |
list, get, create, update, delete |
/datastore, /datastore/{id} |
Datastores |
staticGate |
list, get, create, update, delete |
/static-gate, /static-gate/{id} |
Static gates |
documentation |
list, get, create, update, delete |
/documentation, /documentation/{id} |
Documentation |
batchRequest |
create |
POST /batch-request |
Batch requests |
apiToken |
list, get |
/api-token, /api-token/{id} |
API tokens |
environment |
list, get, update |
/environment, /environment/{id} |
Environments |
category |
list |
/category |
Categories |
log |
list (see Logs) |
/log |
Logs |
integration.install(integrationId, { is_enabled }) and unifiedModel.install(unifiedModelId) install into the environment of your API token.
In version 2.1.0, a few methods don't reach the API: integratedAccount.refreshCredentials, syncJobCronTrigger.schedule, webhook.test, and datastore.test. Call those endpoints with apiClient.request.
The SDK doesn't wrap tenants, session tokens, an integrated account's MCP servers, capabilities, credentials update, bulk delete or validation, sync job templates and run states, unified model mappings, observability destinations, analytics, webhook event history, configuration version history, notification destinations, SSO connections, SCIM, or group mappings. Call those with apiClient.request too.
Available tools
The API marks GET /integrated-account/{id}/tools deprecated for listing what an account supports, which GET /integrated-account/{id}/capabilities does instead; it remains the endpoint for AI tool calling.
The SDK provides a way to discover available tools and their schemas for each integrated account. This is particularly useful when building LLM-powered applications:
// Get the read tools (list and get) for an integrated account.
// Filter by method: 'read', 'write', 'custom', or method names such as ['list', 'get'].
const tools = await trutoApi.integratedAccount.tools(
'766cc1ee-6637-4aa1-a73e-a0c89ccc867c',
['read']
)
console.log(tools)
// Get all tools without filtering by method
const allTools = await trutoApi.integratedAccount.tools(
'766cc1ee-6637-4aa1-a73e-a0c89ccc867c'
)Each tool in the response includes:
resource— The resource name (e.g.,tickets,accounts)method— The available method (e.g.,list,get,create)name— The tool's snake_case identifier (up to 64 characters), for examplelist_all_hub_spot_contacts; pass it to your model as the function namedescription— A description of what the tool doesquery_schema— JSON schema for query parametersbody_schema— JSON schema for request body (if applicable)response_schema— JSON schema for the response (if available)required— Array of required parameter namestags— Tags set on the tool
Truto provides a toolset for Langchain.js as well.
Logs
trutoApi.log.list() reads logs for one log_type at a time: unified_proxy_api, rapid_bridge (sync job runs), webhook (outbound webhook deliveries), mcp, or sync_job_cron_trigger. Without log_type the API answers 400. log_type_filter takes keys specific to that log type, and TypeScript checks them for you:
const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()
const logs = await trutoApi.log
.list({
log_type: 'mcp',
created_at: { gt: weekAgo, lt: new Date().toISOString() },
log_type_filter: { mcp_server_id: 'mcp-server-id', tool_name: 'list_all_zendesk_tickets' },
})
.toArray()log_type |
log_type_filter keys |
|---|---|
unified_proxy_api |
request_type (proxy or unified), integrated_account_id, environment_id, integration |
rapid_bridge |
integrated_account_id, sync_job_run_id, sync_job_id, sync_job_run_event, webhook_id, environment_id, integration |
webhook |
webhook_id, event, integrated_account_id, environment_id, integration |
mcp |
integrated_account_id, mcp_server_id, mcp_method, tool_name, resource, method, client_name, client_version, request_id, environment_id, integration |
sync_job_cron_trigger |
environment_id |
Each filter value can be a string or an array of strings to match any of them. created_at.gt and created_at.lt can be at most one month apart, and lt is required when you set gt.
Request queue
For high-volume API requests with rate limiting, the SDK provides a request queue. It has the unifiedApi and proxyApi methods (except unifiedApi.meta), plus request for apiClient.request:
import TrutoApi, { RequestQueue } from '@truto/truto-ts-sdk'
const truto = new TrutoApi({
token: process.env.TRUTO_API_TOKEN,
baseUrl: process.env.TRUTO_API_BASE_URL,
})
// At most 5 requests in flight and 5 started per second.
// Defaults: concurrency 10, interval 1000 ms, intervalCap 10.
const queue = new RequestQueue(truto, {
concurrency: 5,
interval: 1000,
intervalCap: 5,
})
const response = await queue.proxyApi
.list({
integrated_account_id: '820b732c-bd4d-4b98-b33e-fda752a368ff',
resource: 'tickets',
limit: 10,
})
.toArray()Calling any endpoint
For an endpoint the SDK doesn't wrap, trutoApi.apiClient.request(path, init) sends a request with the same token, retries, and error handling. The path must start with /, and any query string goes in the path. init takes the method, a body (a plain object is sent as JSON), and the options from Retries and timeouts.
const tenants = await trutoApi.apiClient.request('/tenant', { method: 'GET' })
await trutoApi.apiClient.request('/webhook/test', {
method: 'POST',
body: { id: 'webhook-id' },
})
await trutoApi.apiClient.request('/sync-job-cron-trigger/cron-trigger-id/schedule', {
method: 'POST',
})