Skip to content
Weavz
Menu

TypeScript SDK

Official TypeScript SDK for the Weavz API.

The official TypeScript SDK provides a typed, ergonomic interface for the Weavz API.

Installation

bash
npm install @weavz-io/sdk

Quick Start

typescript
import { WeavzClient } from '@weavz-io/sdk'
 
const client = new WeavzClient({
  apiKey: 'wvz_your_api_key',
})
 
// Execute an action
const result = await client.actions.execute('slack', 'send_channel_message', {
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
  integrationAlias: 'office_slack',
  input: { channel: '#general', text: 'Hello from Weavz!' },
})
 
if ('approval' in result) {
  console.log('Approval required:', result.approval.id)
} else {
  console.log('Message sent:', result.output)
}

Configuration

typescript
const client = new WeavzClient({
  apiKey: 'wvz_your_api_key',
  baseUrl: 'https://platform.weavz.io',  // Default
  timeout: 310_000,                 // Request timeout in milliseconds
  maxRetries: 2,                    // Retry count for transient failures
  headers: { 'X-App-Version': '1.0.0' },
  userAgent: 'my-product/1.0.0',
})
OptionRequiredDefaultDescription
apiKeyYes—Your API key (wvz_... prefix)
baseUrlNohttps://platform.weavz.ioAPI base URL
timeoutNo310000Request timeout in milliseconds. Covers 5 minute Code Mode and Sandbox runs plus response overhead.
maxRetriesNo2Number of retries for transient failures
fetchNoglobal fetchCustom fetch implementation for tests, edge runtimes, or instrumentation
headersNo{}Extra headers sent with every request
userAgentNo—User-Agent header value for Node-compatible runtimes
onRetryNo—Callback called before a retryable request is retried

Resources

The client exposes namespaced resources for each API area:

ResourceMethodsDescription
client.mcpWorkspaceslist, create, get, update, delete, configureMcp, createAccessToken, addIntegration, updateIntegrationMCP Workspaces and included endpoints; workspaces remains an alias
client.workspaceslist, create, get, update, delete, listIntegrations, addIntegration, updateIntegration, removeIntegrationWorkspace management
client.connectionslist, get, create, delete, resolveConnection management
client.actionsexecuteExecute integration actions
client.triggerslist, enable, disable, testTrigger management
client.mcpServerslist, create, get, update, delete, regenerateToken, createBearerToken, createAccessToken, createEndUserToken, createOAuthToken, addTool, updateTool, deleteTool, executeCode, getDeclarationsMCP server management
client.apiKeyslist, create, deleteAPI key management
client.integrationslist, listSummary, get, resolveOptions, resolveProperty, oauthStatusIntegration metadata
client.connectcreateToken, poll, wait, getSession, popupHosted connect flow
client.endUserscreate, list, get, update, delete, createConnectToken, inviteEnd-user identity and connect portal management
client.partialslist, get, create, update, delete, setDefaultSaved inputs and enforced fields
client.approvalPolicieslist, create, get, update, delete, testApproval rule management
client.approvalslist, get, approve, reject, cancel, waitApproval request inbox and decisions
client.skillslist, search, get, create, update, deleteOptional reusable task instructions; search is metadata-only
client.computerSessionscreateAccessShort-lived human watch or control link for an existing Computer Control session

Skills are optional instructions; they do not execute tasks or grant app access. Computer session access issues a human viewer link for an existing session. It does not start or provision a computer. Availability depends on your account and configured Computer Control setup. See the Skills guide, Computer Control guide, and computer access API reference.

Resource Options and Defaults

The SDK method names mirror the REST resources. Use the API reference for complete option tables, defaults, and bounds:

Common Operations

Managing Workspaces

typescript
// List workspaces
const { workspaces } = await client.workspaces.list()
 
// Create a workspace
const { workspace } = await client.workspaces.create({
  name: 'My Workspace',
  slug: 'my-workspace',
})
 
// Delete a workspace
await client.workspaces.delete(workspace.id)

Tenant Configuration APIs

Use org-wide API keys for control-plane setup when you are building your own SaaS on top of Weavz.

typescript
const { workspace } = await client.workspaces.create({
  name: 'Production',
  slug: 'production',
})
 
await client.workspaces.addIntegration(workspace.id, {
  integrationName: 'slack',
  alias: 'customer_slack',
  connectionStrategy: 'per_user',
})

Managing Connections

typescript
// Create an API key connection
const { connection } = await client.connections.create({
  type: 'SECRET_TEXT',
  integrationName: 'openai',
  externalId: 'tenant_123_openai',
  displayName: 'OpenAI Key',
  secretText: 'sk-...',
})
 
// Resolve a connection
const resolved = await client.connections.resolve({
  integrationName: 'openai',
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
  externalId: 'tenant_123_openai',
})
 
// Delete a connection
await client.connections.delete(connection.id)

Executing Actions

typescript
const result = await client.actions.execute('github', 'create_issue', {
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
  integrationAlias: 'github_prod',
  input: {
    repository: 'my-org/my-repo',
    title: 'Bug Report',
    body: 'Something went wrong',
    labels: 'bug',
  },
})
 
if ('approval' in result) {
  console.log('Approval required:', result.approval.id)
} else {
  console.log('Issue created:', result.output)
}

MCP Workspaces and Private Access

typescript
const workspaceId = '550e8400-e29b-41d4-a716-446655440000'
 
// Add built-ins to the workspace once. MCP servers sync workspace integrations automatically.
await client.workspaces.addIntegration(workspaceId, {
  integrationName: 'storage',
  alias: 'files',
  settings: { persistence: { scope: 'workspace' } },
})
 
// Read the included endpoint; no separate server creation is needed.
const { workspace } = await client.mcpWorkspaces.get(workspaceId)
const server = workspace.mcpServer!
 
// Issue private MCP access for an existing external end user.
const { accessToken, mcpEndpoint: userEndpoint } = await client.mcpWorkspaces.createAccessToken(
  workspaceId, { endUserId: 'user_123', expiresIn: 3600 },
)
// Deliver accessToken and userEndpoint privately to that user's agent.
 
// Run Code Mode from your own harness
const run = await client.mcpServers.executeCode(server.id, `
  return await weavz.files.write_file({ path: "summary.json", content: JSON.stringify({ status: "ready" }) })
`)
 
// If an approval rule pauses the run, approve it and fetch the stored result.
const approvedRun = await client.mcpServers.executeCode(server.id, {
  approvalId: 'apr_9b36d3f761d84bb2b6f9a0c4b9d1f7e0',
  waitForApprovalSeconds: 30,
})
 
// Use Tool Mode when you want a small explicit surface instead of Code Mode.
await client.workspaces.addIntegration(workspaceId, {
  integrationName: 'slack',
  alias: 'office_slack',
  enabledActions: ['send_channel_message'],
})
const { server: toolServer } = await client.mcpWorkspaces.configureMcp(workspaceId, {
  name: 'Focused Slack Tools',
  mode: 'TOOLS',
  authMode: 'oauth',
})

New MCP Workspaces use Tool Mode and OAuth by default. Switch the endpoint to Code Mode before using the Code Mode examples below. Workspace access tokens work with the endpoint's current authentication mode; send the returned accessToken as Authorization: Bearer to the MCP URL. The older server-specific bearer APIs remain available for explicit bearer-enabled configurations. Shared static bearer credentials are an advanced service option and are never a substitute for individual end-user access.

Code Mode is the default recommendation for broad agent workspaces. It exposes weavz_search, weavz_read_api, and weavz_execute, while getDeclarations() returns full TypeScript declarations with JSDoc and return types. If code passes the wrong input shape, executeCode() returns a tool error with validation details instead of a generic failure. Programmatic Code Mode responses include structuredContent.timings for execution and per-action latency. For Agent Browser workflows, batch several browser actions inside one Code Mode script instead of calling executeCode() once per click or screenshot. Use Tool Mode for small explicit tool surfaces.

Managing Triggers

typescript
// Enable a trigger
const { triggerSource } = await client.triggers.enable({
  integrationName: 'github',
  triggerName: 'new_push',
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
  callbackUrl: 'https://yourapp.com/webhooks/github',
  integrationAlias: 'github_prod',
})
 
// List active triggers
const { triggers } = await client.triggers.list()
 
// Disable a trigger
await client.triggers.disable(triggerSource.id)

Managing Input Partials

typescript
// Create a partial (saved parameter preset)
const { partial } = await client.partials.create({
  name: 'Default Slack Channel',
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
  integrationName: 'slack',
  integrationAlias: 'office_slack',
  actionName: 'send_channel_message',
  values: { channel: '#general' },
  enforcedKeys: ['channel'],
})
 
// List partials for a workspace
const { partials } = await client.partials.list({ workspaceId: '550e8400-e29b-41d4-a716-446655440000' })
 
// Set as default for this action scope
await client.partials.setDefault(partial.id, true)
 
// Use partial with action execution. This uses the dynamic overload because the
// generated Slack type cannot know that the partial supplies `channel`.
const integrationName: string = 'slack'
const result = await client.actions.execute(integrationName, 'send_channel_message', {
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
  integrationAlias: 'office_slack',
  partialIds: [partial.id],
  input: { text: 'Hello!' }, // channel comes from the partial
})
 
if ('approval' in result) {
  console.log('Approval required:', result.approval.id)
} else {
  console.log('Message sent:', result.output)
}
 
// Delete a partial
await client.partials.delete(partial.id)

Hosted Connect Flow

Use the hosted connect page to create OAuth2 connections. The flow is two steps: create a token, then open the popup:

typescript
// On your backend. Use your configured frontend origin, not untrusted input.
const connectClient = new WeavzClient({
  apiKey: process.env.WEAVZ_API_KEY!,
  headers: { Origin: 'https://app.example.com' },
})
const session = await connectClient.connect.createToken({
  integrationName: 'google-sheets',
  connectionName: 'Google Sheets',
  externalId: 'tenant_123_gsheets',
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
})
// Return session.connectUrl to the authorized browser.

Keep the API key on your backend. Set Origin to the exact frontend origin that opens the popup so OAuth completion returns to that page. For multiple frontends, choose it from your server-side allowlist. Prepare the short-lived connect URL before the user clicks Connect. Open the popup directly from that click handler:

typescript
import { openConnectPopup } from '@weavz-io/sdk'
 
async function onConnectClick(connectUrl: string) {
  const result = await openConnectPopup({ connectUrl })
  console.log('Connection created:', result.connectionId)
}

For server-side or custom flows, create a token and open the connect URL manually:

typescript
// Step 1: Create a connect token
const { token, connectUrl } = await client.connect.createToken({
  integrationName: 'google-sheets',
  connectionName: 'Google Sheets',
  externalId: 'tenant_123_gsheets',
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
})
 
// Step 2: Open connectUrl in a browser window...
// The response contains: token, connectUrl, expiresAt
 
const status = await client.connect.wait(token)
if (status.status === 'COMPLETED') {
  console.log('Connection created:', status.connectionId)
}

Error Handling

All API errors throw WeavzError with structured error information:

typescript
import { WeavzClient, WeavzError } from '@weavz-io/sdk'
 
const client = new WeavzClient({ apiKey: 'wvz_your_key' })
 
try {
  await client.actions.execute('slack', 'send_channel_message', {
    workspaceId: '550e8400-e29b-41d4-a716-446655440000',
    input: { channel: 'invalid', text: 'Hello!' },
  })
} catch (err) {
  if (err instanceof WeavzError) {
    console.error(err.message)   // Human-readable error message
    console.error(err.code)      // Machine-readable error code (e.g., "ACTION_FAILED")
    console.error(err.status)    // HTTP status code (e.g., 400)
    console.error(err.details)   // Additional error details (if available)
  }
}

Common Error Codes

CodeDescription
VALIDATION_ERRORInvalid request parameters
ACTION_FAILEDAction execution failed
CONNECTION_REQUIREDAction needs a connection
CONNECTION_NOT_FOUNDConnection doesn't exist
INTEGRATION_NOT_FOUNDInvalid integration name
QUOTA_EXCEEDEDMonthly usage limit reached
RATE_LIMITEDToo many requests

TypeScript Support

The SDK is written in TypeScript and ships with full type definitions. You get autocomplete and type checking for all resource methods and their parameters. Generated integration helpers also give compile-time checks for known integrationName and actionName pairs.

typescript
// Typed integration inputs (generated from integration schemas)
import { integrationActions, integrationNames, isKnownActionName } from '@weavz-io/sdk'
import type {
  ActionInput,
  ActionName,
  ActionPropertyName,
  IntegrationActionKey,
  IntegrationName,
  SlackSendChannelMessageInput,
} from '@weavz-io/sdk'
 
const input: SlackSendChannelMessageInput = {
  channel: '#general',
  text: 'Typed input!',
}
 
const integrationName: IntegrationName = 'slack'
const actionName: ActionName<'slack'> = 'send_channel_message'
const typedInput: ActionInput<'slack', 'send_channel_message'> = input
const propertyName: ActionPropertyName<'slack', 'send_channel_message'> = 'channel'
const actionKey: IntegrationActionKey = 'slack.send_channel_message'
 
console.log(integrationNames.includes(integrationName))
console.log(integrationActions.slack.includes(actionName))
 
await client.actions.execute('slack', 'send_channel_message', {
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
  input: typedInput,
})
 
const dynamicAction = 'send_channel_message'
if (isKnownActionName('slack', dynamicAction)) {
  await client.actions.execute('slack', dynamicAction, {
    workspaceId: '550e8400-e29b-41d4-a716-446655440000',
    input,
  })
}

Key Types

typescript
import type {
  WeavzClient,
  WeavzError,
  InputPartial,
  WorkspaceIntegration,
  EndUser,
  ExecuteActionResponse,
  IntegrationMetadata,
} from '@weavz-io/sdk'
TypeDescription
WeavzClientMain client class with all resource methods
WeavzErrorError class with message, code, status, details
InputPartialPartial preset with values, enforcedKeys, isDefault
WorkspaceIntegrationIntegration instance on a workspace with alias and connection strategy
EndUserWorkspace end-user identity with externalId, email, and metadata
ExecuteActionResponseOpenAPI-generated response wrapper for action execution
IntegrationMetadataOpenAPI-generated integration metadata shape
IntegrationNameLiteral union of generated integration slugs
ActionName<I>Literal union of generated action names for an integration
ActionInput<I, A>Generated input type for an integration/action pair
ActionPropertyName<I, A>Property-name union for a generated action input
IntegrationActionKeyLiteral union of integration.action keys

Integration Input Types

The SDK ships with generated input types for supported integration actions. Import individual input interfaces by pattern:

typescript
import type {
  // Slack
  SlackSendChannelMessageInput,
  SlackSendDirectMessageInput,
  // GitHub
  GithubCreateIssueInput,
  GithubCreatePullRequestInput,
  // Google Sheets
  GoogleSheetsInsertRowInput,
  GoogleSheetsReadRowsInput,
  // ... all integrations follow the same pattern
} from '@weavz-io/sdk'

The naming pattern is {IntegrationName}{ActionName}Input in PascalCase.

For generic code, use the generated maps and guards:

typescript
import {
  integrationActions,
  integrationNames,
  isKnownIntegrationName,
  isKnownActionName,
} from '@weavz-io/sdk'
import type { ActionInput } from '@weavz-io/sdk'
 
function listKnownActions(integrationName: string) {
  if (!isKnownIntegrationName(integrationName)) return []
  return integrationActions[integrationName]
}
 
const input: ActionInput<'http', 'send_request'> = {
  method: 'GET',
  url: 'https://api.example.com/health',
  headers: {},
  queryParams: {},
  authType: 'NONE',
}
 
await client.actions.execute('http', 'send_request', {
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
  input,
})
 
const { options } = await client.integrations.resolveOptions('slack', {
  actionName: 'send_channel_message',
  propertyName: 'channel',
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
  input: {},
})

Known literal pairs are checked by client.actions.execute(), client.integrations.get(), client.integrations.resolveOptions(), and client.integrations.resolveProperty(). Plain strings still work for future or custom integrations, but they use the dynamic fallback type.

AI Framework Adapters

MCP is the primary hosted surface for giving agents access to Weavz. Framework adapters are a compatibility layer for teams that are embedding Weavz into their own agent runtime and need the same configured workspace actions in a framework-native tool format.

The adapters do not expose dashboard administration or platform internals. They transform customer-facing workspace action schemas into the shape each framework expects, then execute through client.actions.execute() with your API key.

typescript
import {
  WeavzClient,
  createMcpServerActionTools,
  toOpenAIResponsesTool,
  toAnthropicTool,
  toVercelAIToolSet,
} from '@weavz-io/sdk'
 
const client = new WeavzClient({ apiKey: process.env.WEAVZ_API_KEY! })
 
// Reuse the action tools configured on an MCP server
const tools = await createMcpServerActionTools(client, '660e8400-e29b-41d4-a716-446655440000')
 
// OpenAI Responses API tool definitions
const openaiTools = tools.map(toOpenAIResponsesTool)
 
// Anthropic tool definitions
const anthropicTools = tools.map(toAnthropicTool)
 
// Vercel AI SDK tools with built-in execution
import { tool, jsonSchema } from 'ai'
const aiSdkTools = toVercelAIToolSet(tools, { tool, jsonSchema })

For manual agent loops, use createToolExecutor() to dispatch tool calls back through client.actions.execute(). The SDK also includes helpers for OpenAI Chat Completions, Google function declarations, and LangChain-style tool objects.

Upgrading to 0.2.0

The 0.2.0 release corrects the customer API contract, request handling, and framework adapters.

  • Nullable response fields now reflect the API. Check for null before using an unassigned workspace, end user, or optional relationship.
  • Google function declarations use parametersJsonSchema rather than parameters, preserving JSON Schema arrays, numeric enums, and unions. Pass the declarations directly to a current Google client. Update code that reads the old field explicitly.
  • Request timeouts, cancellation, malformed responses, and finite retry delays are handled consistently. Action POST requests are not replayed after an ambiguous network failure or server error.
  • MCP adapters retain their configured end-user identity, connection, defaults, and saved input rules. Conflicting bindings and duplicate tool names fail explicitly.

See the customer OpenAPI contract for current request and response shapes.

For browser Hosted Connect, import openConnectPopup without creating an API-key client in the browser. Existing client.connect.popup() calls remain available.