TypeScript SDK
Client options, errors, connecting accounts, tools and the Claude, OpenAI, Vercel AI SDK and LangChain providers.
The TypeScript SDK wraps the REST API: connect accounts, fetch tools in your model's format and run
the tool calls the model makes. It has no runtime dependencies and needs Node 18 or later (it uses
the global fetch).
Install
pnpm add @toolwire/sdk| Import | Contents | Needs |
|---|---|---|
@toolwire/sdk | Toolwire client, errors, wire types | nothing |
@toolwire/sdk/anthropic | AnthropicProvider, toClaudeTool, toolResultsMessage | nothing (works with raw HTTP too) |
@toolwire/sdk/openai | OpenAIProvider, toOpenAIResponsesTool, toOpenAIChatTool | nothing |
@toolwire/sdk/vercel | VercelProvider | ai 5 or later |
@toolwire/sdk/langchain | LangChainProvider | @langchain/core 1.3 or later |
@toolwire/sdk/schema | JSON Schema transforms | nothing |
Server-side only
Your API key acts on every connected account of the project. Keep it on your server: the client
throws browser_not_allowed when it runs where window exists. dangerouslyAllowBrowser: true
turns that check off; only use it for local tools you run yourself.
Client options
import { Toolwire } from "@toolwire/sdk";
const client = new Toolwire({
apiKey: process.env.TOOLWIRE_API_KEY,
baseUrl: "http://localhost:4000",
});| Option | Default |
|---|---|
apiKey | TOOLWIRE_API_KEY; missing throws missing_api_key |
baseUrl | TOOLWIRE_BASE_URL, else the hosted API. A trailing /api/v1 is fine |
provider | RawProvider: tools come back as the API returns them |
timeoutMs | 70000 per attempt (tool execution has a 60 second deadline) |
maxRetries | 2 extra attempts for retryable requests (see below) |
fetch | the global fetch (pass your own for proxies or tests) |
dangerouslyAllowBrowser | false |
Retries
The client retries a request only when running it twice is safe:
- What is retried:
GETrequests, andPOSTrequests sent with anIdempotency-Key. Those aretools.execute,connectedAccounts.initiateandtriggers.create, which send a newcrypto.randomUUID()per call by default, or your own with{ idempotencyKey }as the last argument. A retry resends the same key and body. In a runtime withoutcrypto.randomUUIDno default key is sent, so those calls are not retried unless you pass a key. - On: network errors,
429 rate_limited,502,503and504. A keyedPOSTis also retried on409 idempotency_in_progress. - How often: up to
maxRetriesextra attempts (default2). - Wait: the server's
Retry-After(header, elsedetails.retry_after), capped at 10 seconds; without one, exponential backoff with jitter. - Never retried:
429 quota_exceeded, any other4xx,500, timeouts, andPUT,PATCHandDELETErequests.
See Idempotency and Rate limits. Every request sends
Authorization: Bearer <key>.
Responses are the API's objects, exactly as documented for the REST API: field names are
snake_case (redirect_url, input_schema, log_id). Method parameters are camelCase.
Errors
| Error | When |
|---|---|
ToolwireApiError | The API answered with an error. status, code, message, details and requestId. |
ToolwireInsufficientScopeError | A ToolwireApiError for 403 insufficient_scope: the API key lacks a permission. required names it. |
ToolwireToolNotAllowedError | A ToolwireApiError for 403 tool_not_allowed: the key's tool restriction excludes tool. |
ToolwireError | Raised by the SDK itself, with a code from the list below. |
Client codes: missing_api_key, browser_not_allowed, invalid_filter, auth_config_not_found,
ambiguous_auth_config, connection_failed, connection_timeout, network_error, timeout,
aborted, invalid_response, invalid_idempotency_key (a key that is not 1 to 255 printable
ASCII characters without spaces), plus provider_already_attached and provider_not_attached from
providers.
import { ToolwireApiError, ToolwireError } from "@toolwire/sdk";
try {
await client.tools.retrieve("GITHUB_NOPE");
} catch (err) {
if (err instanceof ToolwireApiError) console.error(err.status, err.code, err.requestId);
else if (err instanceof ToolwireError) console.error(err.code, err.message);
}ToolwireApiError extends ToolwireError, and the two scope errors extend ToolwireApiError, so
check the most specific class first. Include requestId when you contact
support. On 429 rate_limited and 409 idempotency_in_progress, retryAfter holds the seconds
the server asked you to wait; quota_exceeded has none. The codes are listed in
Errors.
Two more resources read your project's records: usage.retrieve({ from, to, granularity })
returns the usage totals and series (see Usage and billing), and
auditLogs.list({ action, actorType, actorId, targetId, from, to, limit, cursor }) pages through
the audit log (see Audit logs).
Restricted API keys
An API key can be limited to some permissions and tools. whoami() shows the
key's access: permissions is null for full access, and allowed_toolkits and allowed_tools
are both null without a tool restriction.
import { ToolwireInsufficientScopeError, ToolwireToolNotAllowedError } from "@toolwire/sdk";
const me = await client.whoami();
console.info(me.api_key.permissions ?? "full access", me.api_key.allowed_toolkits);
try {
await client.tools.execute("GITHUB_CREATE_ISSUE", {
userId: "user_123",
arguments: { owner: "acme", repo: "widgets", title: "Bug report" },
});
} catch (err) {
if (err instanceof ToolwireToolNotAllowedError) console.error(`key may not use ${err.tool}`);
else if (err instanceof ToolwireInsufficientScopeError) console.error(`needs ${err.required}`);
else throw err;
}tools.listandtools.getby toolkit return only the tools the key may use.tools.retrieve,tools.executeandtools.get(userId, { tools: [...] })naming another tool throwToolwireToolNotAllowedError.- Inside
handleToolCalls(and the Vercel and LangChain tool executors),tool_not_allowedis returned to the model as a tool error withdetails.tool, so the model can explain it.insufficient_scopeis thrown: it is a setup problem, not something the model can fix. - Neither is retried.
Connect accounts
const conn = await client.connectedAccounts.initiate({
userId: "user_123",
toolkit: "github",
callbackUrl: "https://app.example.com/settings/integrations",
});
// send the user to conn.redirect_url
const account = await client.connectedAccounts.waitForConnection(conn.id, {
timeoutMs: 120_000,
});initiate({ toolkit })looks up the toolkit's enabled auth configs. Exactly one is used; none throwsauth_config_not_found; several throwambiguous_auth_configwith their ids, so passauthConfigIdinstead oftoolkit.- For API key and bearer toolkits, pass
credentials: { value }to store the user's key directly. Forfieldstoolkits (most catalog apps) passcredentials: { fields: { auth_id: "...", auth_token: "..." } }.redirect_urlis thennull. waitForConnection(id, { timeoutMs, intervalMs, signal })polls everyintervalMs(default 2000, minimum 500) until the account isactive. Afailed,expiredorrevokedaccount throwsconnection_failedwith the status and reason indetails; aftertimeoutMs(default 5 minutes) it throwsconnection_timeout.reconnect(id, { callbackUrl, credentials })returns a freshredirect_urlfor the same account, or withcredentialsstores the new ones at once (redirect_url: null).- Also available:
retrieve(id),list({ userId, toolkit, status, authConfigId, scope, limit, cursor })(returns{ data, next_cursor }) anddelete(id).
Shared accounts (0.20.0)
A shared account belongs to the project: every member can use it in Claude and automations (see Personal and shared accounts).
import { isSharedAccountError, SHARED_USER_ID } from "@toolwire/sdk";
const shared = await client.connectedAccounts.initiate({
toolkit: "gmail",
scope: "shared",
label: "Sales inbox", // optional: omitted, it is named after the account, "Gmail (sales@acme.com)"
});
// shared.user_id === SHARED_USER_ID ("__shared__"); no userId is passed for shared accounts.
await client.connectedAccounts.update(shared.id, { label: "Support inbox" });
// or: await client.connectedAccounts.rename(shared.id, "Support inbox");
const { data } = await client.connectedAccounts.list({ scope: "shared", toolkit: "gmail" });
try {
await client.connectedAccounts.rename(shared.id, "Sales inbox");
} catch (err) {
if (isSharedAccountError(err, "label_taken")) {
// another shared Gmail account already has this name (any letter case)
}
}Share an account you already connected, or give a shared one back (0.21.0):
const team = await client.connectedAccounts.share(personal.id, "Sales inbox"); // label optional
try {
await client.connectedAccounts.unshare(team.id); // back to the member who connected it
} catch (err) {
if (isSharedAccountError(err, "account_in_use")) {
// err.details: { automations: [{ id, name }], triggers: [{ id, trigger_slug }] }
}
}isSharedAccountError(err, code?)narrows to the shared-account errors:label_taken,shared_accounts_limit,no_connectorandaccount_in_use(409),shared_connection_restrictedandshare_restricted(403) andnot_shared(400).- To execute with a shared account, pass its
connectedAccountId.SHARED_USER_IDis reserved: it cannot be a personal account's user id, an MCP user URL's user or an automation owner.
Toolkits and categories
// One page: { data, next_cursor, total }.
const page = await client.toolkits.list({ category: "ai", limit: 50 });
const next = page.next_cursor
? await client.toolkits.list({ category: "ai", limit: 50, cursor: page.next_cursor })
: null;
// Every page, fetched as you iterate.
for await (const toolkit of client.toolkits.listAll({ source: "catalog" })) {
console.log(toolkit.slug, toolkit.auth_schemes);
}
const categories = await client.toolkitCategories.list({ search: "mail" });
const schemes = await client.toolkits.authSchemes("plivo");
// Replace the credentials of a fields account without a redirect.
await client.connectedAccounts.reconnect("ca_...", {
credentials: { fields: { auth_id: "MA123", auth_token: newAuthToken } },
});toolkits.list({ category, search, source, featured, limit, cursor })returns one page (default 50, at most 200).listAll(params)followsnext_cursorfor you, 200 per request.toolkitCategories.list({ search, source })returns the 17 categories with counts.toolkits.authSchemes(slug)returns the auth schemes of a toolkit, with thefieldsto ask for and the OAuthredirect_uri.toolkits.retrieve(slug)andauthConfigs.list({ toolkit })read one toolkit and your auth configs.
Breaking in 0.9.0: toolkits.list and tools.list return one page instead of every item.
Use listAll where you read them all. tools.get and the providers still return every matching
tool.
Tools
const listed = await client.tools.list({ toolkits: ["github"], search: "issue" });
const one = await client.tools.retrieve("GITHUB_CREATE_ISSUE");
const tools = await client.tools.get("user_123", { tools: ["GITHUB_CREATE_ISSUE"] });
const res = await client.tools.execute("GITHUB_CREATE_ISSUE", {
userId: "user_123",
arguments: { owner: "acme", repo: "api", title: "Flaky test in CI" },
});listreturns one page of raw tools ({ data, next_cursor }, default 100, at most 200 per page) andlistAlliterates over every page.retrievereturns one raw tool.get(userId, filter)returns every matching tool in the provider's format, bound to that user, and requirestoolkitsortools(at most 20 each).search,tagsandincludeDeprecatedfilter the toolkit listing.executeruns asuserId(the newest active account for the tool's toolkit) or asconnectedAccountId. It resolves with{ successful, data, error, log_id, ... }: a tool that ran and failed issuccessful: false, not an exception.
MCP servers
Create MCP servers and per-user URLs from code, and read the calls made through them.
Each call needs the matching permission: mcp_server:read or
mcp_server:write, and logs:read for execution logs.
const server = await client.mcpServers.create({
name: "Support agent",
toolkits: ["github", "slack"],
allowedTools: ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"], // omit: every tool of the toolkits
allowedOrigins: ["https://app.example.com"], // browsers may call the user URLs from here
});
// One URL per end user. The URL is a credential and is returned only now.
const { url } = await client.mcpServers.userTokens.create(server.id, {
userId: "user_123",
expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
});
// The calls made through this server, newest first.
for await (const log of client.toolExecutions.listAll({ mcpServerId: server.id })) {
console.info(log.created_at, log.tool_slug, log.status);
}| Method | API |
|---|---|
mcpServers.list() | GET /mcp_servers, every server, newest first |
mcpServers.create({ name, toolkits, allowedTools?, authConfigIds?, allowedOrigins? }) | POST /mcp_servers |
mcpServers.get(id), update(id, { ..., status? }), delete(id) | GET, PATCH, DELETE /mcp_servers/{id} |
mcpServers.userTokens.list(serverId, { userId?, status?, limit?, cursor? }), listAll | GET /mcp_servers/{id}/user_tokens, { data, next_cursor } |
mcpServers.userTokens.create(serverId, { userId, expiresAt? }) | POST /mcp_servers/{id}/user_tokens, the url is shown only here |
mcpServers.userTokens.revoke(serverId, tokenId) | POST /mcp_servers/{id}/user_tokens/{token_id}/revoke |
toolExecutions.list({ tool?, toolkit?, status?, source?, mcpServerId?, automationRunId?, from?, to?, limit?, cursor? }), listAll | GET /logs/tools, newest first |
toolExecutions.get(id) | GET /logs/tools/{id}, with the redacted input and output |
server.api_key_url(/s/<id>/mcp) needs a project API key and acts for any user: keep it on your backend. A user URL (/u/...) acts for one user and is what goes into that user's MCP client. Revoking it or deleting the server stops it at once.allowedOrigins(up to 10 exact origins) lets browser MCP clients call the user URLs; see Browser access.- A key with a tool restriction can't hold
mcp_server:write, so it can't create servers or user URLs that would expose other tools.
Managed servers. Every McpServer has a kind (type McpServerKind): "custom" for the
servers you create, or "all_connected" for the project's one managed server,
the one behind Connect to agents. mcpServers.create always makes a
custom server; the managed one only appears once a member creates a agent link, and
mcpServers.list() returns it with the others.
- Its
toolkitsandallowed_toolsare[]: what a user URL exposes is that user's connected toolkits at request time. Itstools_countis an upper bound over every user of the project. mcpServers.updatemay changename,statusandallowedOriginson it.toolkits,allowedToolsorauthConfigIdsthrow aToolwireApiErrorwith status400, codevalidation_erroranddetails.fieldErrors.<field>set to["Managed by Connect to Claude"].mcpServers.userTokens.createworks on it for anyuserId: a URL with every app that user has connected.mcpServers.deleteremoves it with every URL on it, agent links included.- agent links themselves have no SDK method: they are personal and need a dashboard session.
triggers.sendTestEvent(id) sends a test event to a
trigger's destination and returns the new delivery.
Automations
The SDK has no automations methods yet; build automations in the dashboard or call the
REST routes with your own HTTP client. Version 0.17.0 adds what you
need to read their results:
- Types
Automation,AutomationGraph,AutomationStatus,AutomationList,AutomationRun,AutomationRunStatus,AutomationRunKind,AutomationStepRun,AutomationRunListandAutomationTemplate, generated from the API, for the JSON those routes return. ToolExecutionSourceincludes"automation", and execution log rows haveautomation_run_id.toolExecutions.list({ source: "automation", automationRunId: "arun_..." })(andlistAll) returns the executions of one run's steps.Triggerhasautomation_id. On a trigger managed by an automation,triggers.update,delete,enable,disable,rotateSecret,sendTestEventandtriggers.deliveries.redeliverthrow aToolwireApiErrorwith status409and codemanaged_by_automation;details.automation_idnames the automation.ApiKeyPermissionincludes"automation:read"and"automation:write", soToolwireInsufficientScopeError.requiredcan name them.
Providers
A provider converts tools for one framework and runs that framework's tool calls. Pass it to the
client; client.provider is then typed, and tools.get returns that framework's tool type.
One provider instance belongs to one client. Passing the same instance to a second client throws
provider_already_attached, because its tools would otherwise run with the second client's API key.
Create one provider per client.
When a tool call fails in a way the model can act on (the tool failed, invalid arguments, unknown
tool, no connected account, connection not active) the model gets an error result and can tell the
user to connect or reconnect. Developer problems (invalid API key, 403, 5xx, network) are
thrown. The Claude, OpenAI and LangChain providers cut results longer than 100,000 characters and
mark them [truncated: ...] (option maxResultChars).
Claude
AnthropicProvider returns Claude tool definitions and runs the tool_use blocks of a response.
The loop stays in your code: you choose the model, history and turn limit.
import Anthropic from "@anthropic-ai/sdk";
import { Toolwire } from "@toolwire/sdk";
import { AnthropicProvider, toolResultsMessage } from "@toolwire/sdk/anthropic";
const anthropic = new Anthropic(); // reads ANTHROPIC_API_KEY
const toolwire = new Toolwire({ provider: new AnthropicProvider() });
const userId = "user_123";
const tools = await toolwire.tools.get(userId, { tools: ["GITHUB_CREATE_ISSUE"] });
const messages: Anthropic.MessageParam[] = [
{ role: "user", content: "Open an issue in acme/widgets: the README has a broken link." },
];
for (let turn = 0; turn < 8; turn++) {
const response = await anthropic.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
tools,
messages,
});
if (response.stop_reason === "refusal") break; // declined: nothing to run
// Append the full content (thinking and tool_use blocks included), unchanged.
messages.push({ role: "assistant", content: response.content });
if (response.stop_reason !== "tool_use") break;
const results = await toolwire.provider.handleToolCalls(userId, response);
messages.push(toolResultsMessage(results)); // all results in one user message
}handleToolCalls(userId, response)returns onetool_resultpertool_useblock, in order, and returns[]unlessstop_reasonis"tool_use". Failures come back withis_error: true.- Send all results of a turn in one user message (
toolResultsMessage). Do not setthinkingor forcetool_choice, and do not prefill the assistant turn; the adapter never sets request parameters for you. - Options:
new AnthropicProvider({ strict, maxResultChars, concurrency }).concurrency(default 4) caps parallel tool calls per response.strict: trueemits strict tool schemas where possible; tools with free-form objects, such as the catalog request tools, are sent withoutstrict. - A user with several accounts for one toolkit: pass
{ connectedAccountIds: { github: "ca_..." } }as the third argument. - One provider serving several agents: pass
{ allowedTools: ["GITHUB_CREATE_ISSUE"] }in the same third argument (Anthropic and OpenAI providers) so a call for any other tool returns atool_not_allowederror result and never runs. - The same loop works with
anthropic.beta.messages.create, for example to turn on the server-side refusal fallback withbetas: ["server-side-fallback-2026-07-01"]andfallbacks: "default".handleToolCallsaccepts beta responses too. The repository'sexamples/claude-github-issueagent does this and also stops onmax_tokenswithout running a cut-off tool call.
OpenAI
OpenAIProvider targets the Responses API by default and Chat Completions with
{ api: "chat" }.
import OpenAI from "openai";
import { Toolwire } from "@toolwire/sdk";
import { OpenAIProvider } from "@toolwire/sdk/openai";
const openai = new OpenAI();
const toolwire = new Toolwire({ provider: new OpenAIProvider() }); // Responses API
const model = process.env.OPENAI_MODEL!; // any model with function calling
const tools = await toolwire.tools.get("user_123", { toolkits: ["github"] });
let response = await openai.responses.create({
model,
tools,
input: "Open an issue in acme/widgets: the README has a broken link.",
});
const outputs = await toolwire.provider.handleToolCalls("user_123", response);
if (outputs.length > 0) {
response = await openai.responses.create({
model,
tools,
previous_response_id: response.id,
input: outputs,
});
}
console.log(response.output_text);With { api: "chat" }, pass the completion (or its message) to handleToolCalls and append the
returned role: "tool" messages after the assistant message. Descriptions are cut to 1024
characters, the OpenAI limit.
Strict mode. The OpenAI provider emits strict schemas by default (strict: true): every object
is closed, every property is required, and optional properties become nullable. Before a tool runs,
null for an originally optional field is removed again, because our schemas do not accept null
there. Tools that use keywords outside OpenAI's strict subset (for example allOf, conditionals or
record-style objects) are sent with their original schema and strict: false instead of failing.
That includes every catalog app's <SLUG>_SEND_REQUEST and
<SLUG>_SEND_GRAPHQL_REQUEST, whose query and variables are free-form objects.
Pass { strict: false } to turn strict mode off for every tool.
Vercel AI SDK
VercelProvider returns a tool set keyed by tool slug, with execute bound to the user.
import { anthropic } from "@ai-sdk/anthropic";
import { generateText, stepCountIs } from "ai";
import { Toolwire } from "@toolwire/sdk";
import { VercelProvider } from "@toolwire/sdk/vercel";
const toolwire = new Toolwire({ provider: new VercelProvider() });
const tools = await toolwire.tools.get("user_123", { toolkits: ["github"] });
const { text } = await generateText({
model: anthropic("claude-opus-5-5"),
tools,
stopWhen: stepCountIs(5),
prompt: "Open an issue in acme/widgets: the README has a broken link.",
});
console.log(text);A tool returns its data on success and { error: { code, message } } on failure, which the
model sees.
LangChain
LangChainProvider returns structured tools; each returns a JSON string.
import { ChatAnthropic } from "@langchain/anthropic";
import { HumanMessage, type BaseMessage } from "@langchain/core/messages";
import { Toolwire } from "@toolwire/sdk";
import { LangChainProvider } from "@toolwire/sdk/langchain";
const toolwire = new Toolwire({ provider: new LangChainProvider() });
const tools = await toolwire.tools.get("user_123", { toolkits: ["github"] });
const model = new ChatAnthropic({ model: "claude-opus-5-5" }).bindTools(tools);
const messages: BaseMessage[] = [
new HumanMessage("Open an issue in acme/widgets: the README has a broken link."),
];
const ai = await model.invoke(messages);
messages.push(ai);
const stopReason = ai.response_metadata.stop_reason;
if (stopReason === "refusal" || stopReason === "max_tokens") {
// Declined, or cut off mid tool call: run nothing.
console.log(`Stopped: ${stopReason}`);
} else {
for (const call of ai.tool_calls ?? []) {
const tool = tools.find((t) => t.name === call.name);
if (tool) messages.push(await tool.invoke(call));
}
}Check response_metadata.stop_reason before running tool calls: on "refusal" the model declined,
and on "max_tokens" the last tool call may be cut off, so stop without running anything.
Schema transforms
@toolwire/sdk/schema holds the pure functions the providers use, for when you call a model API
directly. Each takes a tool's input_schema and returns a new schema.
| Function | Result |
|---|---|
toClaudeStrictSchema(s) | Closed objects for Claude strict tools. Throws SchemaTransformError for record objects. |
toOpenAIStrictSchema(s) | { schema, strict }: strict is false when the schema is outside the strict subset. |
stripNullsForOptional(a, s) | Removes null from arguments where the original schema had an optional field. |
toGeminiSchema(s) | Gemini's schema subset: $ref inlined, nullable instead of null unions, extra keywords dropped. |
Next steps
- Expose the same tools to MCP clients such as Claude Desktop: MCP.
- Read how execution, results and logs work: Execute tools.

