TypeScript SDK

Official TypeScript SDK for the Weavz API.

TypeScript SDK

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

Installation

bash
npm install @weavz/sdk

Quick Start

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

Configuration

typescript
const client = new WeavzClient({
  apiKey: 'wvz_your_api_key',
  baseUrl: 'https://api.weavz.io',  // Default
  timeout: 30_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
apiKeyYesYour API key (wvz_... prefix)
baseUrlNohttps://api.weavz.ioAPI base URL
timeoutNo30000Request timeout in milliseconds
maxRetriesNo2Number of retries for transient failures
fetchNoglobal fetchCustom fetch implementation for tests, edge runtimes, or instrumentation
headersNo{}Extra headers sent with every request
userAgentNoSDK defaultUser-Agent header value for Node-compatible runtimes
onRetryNoCallback called before a retryable request is retried

Resources

The client exposes namespaced resources for each API area:

ResourceMethodsDescription
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, setDefaultInput partial presets
client.approvalPolicieslist, create, get, update, delete, testHuman Gates policy management
client.approvalslist, get, approve, reject, cancel, waitApproval request inbox and decisions

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 { output } = 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',
  },
})

Managing MCP Servers

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: 'datetime',
  alias: 'datetime',
})
await client.workspaces.addIntegration(workspaceId, {
  integrationName: 'hash-encode',
  alias: 'hash',
})
 
// Create a Code Mode MCP server for broad agent workspaces
const { server, mcpEndpoint } = await client.mcpServers.create({
  name: 'AI Agent Workspace',
  mode: 'CODE',
  workspaceId,
  authMode: 'oauth_and_bearer',
  endUserAccess: 'restricted',
  settings: { codeMode: { approvalWaitSeconds: 30 } },
})
 
// Give a known end user programmatic bearer MCP access
const { bearerToken, mcpEndpoint: userEndpoint } = await client.mcpServers.createBearerToken(
  server.id,
  {
    endUserId: 'user_123',
    scopes: ['mcp:tools', 'mcp:code'],
    expiresIn: 60 * 60 * 24 * 30,
  },
)
 
// Run Code Mode from your own harness
const run = await client.mcpServers.executeCode(server.id, `
  const parsed = await weavz.datetime.parse_date({ dateString: "2026-05-18" })
  const digest = await weavz.hash.hash({ text: parsed.iso, algorithm: "sha256", encoding: "hex" })
  return { parsed, digest }
`)
 
// If Human Gates 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: 'slack_bot',
  enabledActions: ['send_channel_message'],
})
const { server: toolServer } = await client.mcpServers.create({
  name: 'Focused Slack Tools',
  mode: 'TOOLS',
  workspaceId,
  authMode: 'oauth',
})

New MCP servers use OAuth by default. Bearer-enabled servers can issue API-created mcp_ tokens scoped to one end user through createBearerToken(). Shared static bearer tokens are returned only when authMode is bearer or oauth_and_bearer and the workspace can safely use service-style 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. 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: 'slack_bot',
  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
const { output } = await client.actions.execute('slack', 'send_channel_message', {
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
  integrationAlias: 'slack_bot',
  partialIds: [partial.id],
  input: { text: 'Hello!' }, // channel comes from the partial
})
 
// 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
// Step 1: Create a connect session
const session = await client.connect.createToken({
  integrationName: 'google-sheets',
  connectionName: 'Google Sheets',
  externalId: 'tenant_123_gsheets',
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
})
 
// Step 2: Open the popup (browser environments)
const result = await client.connect.popup({
  token: session.token,
  connectUrl: session.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/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.

typescript
// Typed integration inputs (generated from integration schemas)
import type { SlackSendChannelMessageInput } from '@weavz/sdk'
 
const input: SlackSendChannelMessageInput = {
  channel: '#general',
  text: 'Typed input!',
}
 
await client.actions.execute('slack', 'send_channel_message', {
  workspaceId: '550e8400-e29b-41d4-a716-446655440000',
  input,
})

Key Types

typescript
import type {
  WeavzClient,
  WeavzError,
  InputPartial,
  WorkspaceIntegration,
  EndUser,
  ExecuteActionResponse,
  IntegrationMetadata,
} from '@weavz/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

Integration Input Types

The SDK ships with generated input types for all 500+ integrations. Import them by pattern:

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

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

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/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.