View as Markdown

Options

Complete API reference for the Integrate SDK

createMCPClient

Creates a new MCP client instance.

function createMCPClient(config: MCPClientConfig): MCPClient;

Parameters

export interface MCPClientConfig<TIntegrations extends readonly MCPIntegration[]> {
  /** Array of integrations to enable */
  integrations: TIntegrations;

Returns

An MCPClient instance.

Example

const client = createMCPClient({
  integrations: [
    githubIntegration({
      clientId: process.env.GITHUB_CLIENT_ID!,
      clientSecret: process.env.GITHUB_CLIENT_SECRET!,
    }),
  ],
  timeout: 60000,
  headers: {
    "User-Agent": "my-app/1.0.0",
  },
  clientInfo: {
    name: "my-app",
    version: "1.0.0",
  },
});

MCPClient

The main client class for interacting with the MCP server.

connect()

Establishes connection to the MCP server.

async connect(): Promise<void>

Example:

await client.connect();

disconnect()

Closes the connection to the MCP server.

async disconnect(): Promise<void>

Example:

await client.disconnect();

Typed Integration Methods

Built-in integrations (GitHub, Gmail) provide fully typed methods for calling tools.

GitHub Integration Methods:

client.github.createIssue(params);
client.github.listIssues(params);
client.github.getRepo(params);
client.github.createPullRequest(params);
// ... and more

Gmail Integration Methods:

client.gmail.sendEmail(params);
client.gmail.listEmails(params);
client.gmail.searchEmails(params);
client.gmail.createLabel(params);
// ... and more

Server Methods:

client.server.listToolsByIntegration(params);
client.server.listAllProviders();
client.server.listConfiguredIntegrations();
// ... other server-level tools

Example:

// Fully typed with IntelliSense support
const result = await client.github.createIssue({
  owner: "owner",
  repo: "repo",
  title: "Bug report",
  body: "Description",
});

_callToolByName()

For integrations configured with genericOAuthIntegration or createSimpleIntegration, use this internal method to call tools directly.

async _callToolByName(name: string, args?: Record<string, any>): Promise<MCPToolCallResponse>

Parameters:

  • name - Full tool name (e.g., 'slack_send_message')
  • args - Tool arguments as key-value pairs (optional)

Returns:

  • MCPToolCallResponse - Tool execution result

Example:

const result = await client._callToolByName("slack_send_message", {
  channel: "#general",
  text: "Hello!",
});

getTool()

Gets a specific tool definition.

getTool(name: string): MCPTool | undefined

Parameters:

  • name - Tool name

Returns:

  • MCPTool or undefined if not found

Example:

const tool = client.getTool("github_create_issue");
console.log(tool?.inputSchema);

getEnabledTools()

Gets all enabled tools (filtered by integrations).

getEnabledTools(): MCPTool[]

Returns:

  • Array of MCPTool objects

Example:

const tools = client.getEnabledTools();
console.log(
  "Enabled tools:",
  tools.map((t) => t.name)
);

getAvailableTools()

Gets all available tools from the server (unfiltered).

getAvailableTools(): MCPTool[]

Returns:

  • Array of MCPTool objects

Example:

const tools = client.getAvailableTools();
console.log(
  "All tools:",
  tools.map((t) => t.name)
);

getOAuthConfig()

Gets OAuth configuration for a specific integration.

getOAuthConfig(integrationId: string): OAuthConfig | undefined

Parameters:

  • integrationId - Integration identifier

Returns:

  • OAuthConfig or undefined if not found

Example:

const config = client.getOAuthConfig("github");
console.log("Scopes:", config?.scopes);

getAllOAuthConfigs()

Gets all OAuth configurations.

getAllOAuthConfigs(): Map<string, OAuthConfig>

Returns:

  • Map of integration IDs to OAuth configurations

Example:

const configs = client.getAllOAuthConfigs();
for (const [integrationId, config] of configs) {
  console.log(`${integrationId}: ${config.provider}`);
}

onMessage()

Registers a message handler.

onMessage(handler: (message: any) => void): () => void

Parameters:

  • handler - Function to handle messages

Returns:

  • Unsubscribe function

Example:

const unsubscribe = client.onMessage((message) => {
  console.log("Message:", message);
});
 
// Later...
unsubscribe();

isConnected()

Checks if the client is connected.

isConnected(): boolean

Returns:

  • true if connected, false otherwise

Example:

if (client.isConnected()) {
  console.log("Client is connected");
}

isInitialized()

Checks if the client is initialized.

isInitialized(): boolean

Returns:

  • true if initialized, false otherwise

Example:

if (client.isInitialized()) {
  console.log("Client is initialized");
}

getAuthState()

Gets authentication state for a specific provider.

getAuthState(provider: string): { authenticated: boolean; lastError?: AuthenticationError } | undefined

Parameters:

  • provider - Provider identifier (e.g., 'github', 'gmail')

Returns:

  • Authentication state object or undefined if provider not found

Example:

const authState = client.getAuthState("github");
if (authState) {
  console.log("Authenticated:", authState.authenticated);
  if (authState.lastError) {
    console.log("Last error:", authState.lastError.message);
  }
}

isProviderAuthenticated()

Checks if a specific provider is authenticated.

isProviderAuthenticated(provider: string): boolean

Parameters:

  • provider - Provider identifier

Returns:

  • true if authenticated, false otherwise

Example:

if (client.isProviderAuthenticated("github")) {
  console.log("GitHub is authenticated");
}

reauthenticate()

Manually triggers re-authentication for a provider.

async reauthenticate(provider: string): Promise<boolean>

Parameters:

  • provider - Provider identifier

Returns:

  • true if re-authentication succeeded, false otherwise

Throws:

  • Error if provider not found or no re-auth handler configured

Example:

try {
  const success = await client.reauthenticate("github");
  if (success) {
    console.log("Re-authentication successful");
  }
} catch (error) {
  console.error("Re-authentication failed:", error);
}

Server Namespace Methods

The server namespace provides access to server-level tools and utilities that don't belong to a specific integration.

client.server.listAllProviders()

List all providers available on the MCP server.

async listAllProviders(): Promise<MCPToolCallResponse>

Returns:

  • MCPToolCallResponse - Response containing all available providers

Example:

const result = await client.server.listAllProviders();
console.log("All providers:", result);

client.server.listToolsByIntegration()

List all tools available for a specific integration.

async listToolsByIntegration(params: {
  integration: string;
}): Promise<MCPToolCallResponse>

Parameters:

  • params.integration (string) - The integration identifier (e.g., "github", "gmail")

Returns:

  • MCPToolCallResponse - Response containing tools for the specified integration

Example:

// List all GitHub tools
const result = await client.server.listToolsByIntegration({
  integration: "github",
});
 
console.log("GitHub tools:", result);

client.server.listConfiguredIntegrations()

List integrations configured for your application. The behavior depends on how you created your client:

  • Default client (import { client } from 'integrate-sdk'): Fetches from server to get integrations configured via createMCPServer()
  • Custom client (createMCPClient({ integrations: [...] })): Returns local config (no server call)
  • Server client (createMCPServer): Returns local config (they ARE the server)
async listConfiguredIntegrations(options?: {
  includeToolMetadata?: boolean;
}): Promise<{
  integrations: ConfiguredIntegration[];
}>

Parameters:

  • options (optional) - Configuration options
    • includeToolMetadata (boolean, default: false) - If true, fetches full tool metadata from the server for all configured integrations. Uses batched requests with concurrency control to avoid rate limiting.

Returns:

  • Object with integrations array containing:
    • id (string) - Integration identifier
    • name (string) - Integration display name
    • logoUrl (string | undefined) - URL to the integration's logo image
    • tools (readonly string[]) - Array of tool names available for this integration
    • hasOAuth (boolean) - Whether the integration requires OAuth
    • scopes (readonly string[] | undefined) - OAuth scopes if applicable
    • provider (string | undefined) - OAuth provider name if applicable
    • description (string | undefined) - Short library blurb from the integration or the SDK catalog
    • category (string | undefined) - Library grouping label (e.g. Productivity, Business) from the integration or the SDK catalog
    • toolMetadata (ToolMetadata[] | undefined) - Full tool metadata when includeToolMetadata: true is passed

Example (default client - fetches from server):

import { client } from "integrate-sdk";
 
// Fetches from server to get what's actually configured
const { integrations } = await client.server.listConfiguredIntegrations();
 
console.log(`Server has ${integrations.length} integrations:`);
integrations.forEach((integration) => {
  console.log(`- ${integration.name} (${integration.id})`);
});

Example (custom client - local config):

import { createMCPClient, githubIntegration } from "integrate-sdk";
 
const customClient = createMCPClient({
  integrations: [githubIntegration()],
});
 
// Returns local config - no server call
const { integrations } = await customClient.server.listConfiguredIntegrations();
// Returns [{ id: 'github', ... }]

Example (with metadata - includes server calls):

// Get configured integrations with full tool metadata
const { integrations } = await client.server.listConfiguredIntegrations({
  includeToolMetadata: true,
});
 
integrations.forEach((integration) => {
  console.log(`${integration.name}:`);
  integration.toolMetadata?.forEach((tool) => {
    console.log(`  - ${tool.name}`);
    console.log(`    ${tool.description}`);
    if (tool.inputSchema) {
      console.log(`    Required: ${tool.inputSchema.required?.join(', ') || 'none'}`);
    }
  });
});

Note:

  • The default client fetches from the server because it has all integrations pre-configured but only some may be configured on the server with OAuth credentials.
  • Custom clients return local config because the developer explicitly chose which integrations to use.
  • With includeToolMetadata: true, it fetches tool metadata for all integrations using batched requests with concurrency control (3 parallel requests at a time) to avoid rate limiting.
  • If metadata fetching fails for an integration, it returns an empty array for that integration's toolMetadata rather than failing the entire operation.

Type Definitions

MCPTool

export interface MCPTool {
  name: string;

MCPToolCallResponse

export interface MCPToolCallResponse {
  content: Array<{
    type: "text" | "image" | "resource";

MCPToolCallParams

export interface MCPToolCallParams {
  name: string;

OAuthConfig

export interface OAuthConfig {
  /** OAuth provider identifier (e.g., 'github', 'google') */
  provider: string;

MCPIntegration

export interface MCPIntegration<TId extends string = string> {
  /** Unique integration identifier */
  id: TId;

ConfiguredIntegration

export interface ConfiguredIntegration {
  id: string;

ReauthContext

export interface ReauthContext {
  /** The integration/provider that needs re-authentication */
  provider: string;

OAuth Types

PopupOptions

export interface PopupOptions {
  /** Window width in pixels (default: 600) */
  width?: number;

OAuthFlowConfig

export interface OAuthFlowConfig {
  /** How to display OAuth authorization */
  mode: 'popup' | 'redirect';

AuthStatus

export interface AuthStatus {
  /** Whether the provider is authorized */
  authorized: boolean;

ProviderTokenData

export interface ProviderTokenData {
  /** Stable session token for MCP requests */
  sessionToken?: string;

OAuthCallbackParams

export interface OAuthCallbackParams {
  /** Authorization code from OAuth provider */
  code: string;

OAuth Event Types

AuthStartedEvent

export interface AuthStartedEvent {
  /** Provider being authorized */
  provider: string;

AuthCompleteEvent

export interface AuthCompleteEvent {
  /** Provider that was authorized */
  provider: string;

AuthErrorEvent

export interface AuthErrorEvent {
  /** Provider that failed authorization */
  provider: string;

AuthLogoutEvent

export interface AuthLogoutEvent {
  // Empty for now, could add metadata later
}

/**
 * Event payload for auth:disconnect event (provider-specific)
 */

AuthDisconnectEvent

export interface AuthDisconnectEvent {
  /** Provider that was disconnected */
  provider: string;

Built-in Integrations

githubIntegration()

Creates a GitHub integration.

function githubIntegration(config: GitHubIntegrationConfig): MCPIntegration;
export interface GitHubIntegrationConfig {
  /** GitHub OAuth client ID (defaults to GITHUB_CLIENT_ID env var) */
  clientId?: string;

gmailIntegration()

Creates a Gmail integration.

function gmailIntegration(config: GmailIntegrationConfig): MCPIntegration;
export interface GmailIntegrationConfig {
  /** Google OAuth client ID (defaults to GMAIL_CLIENT_ID env var) */
  clientId?: string;

genericOAuthIntegration()

Creates a generic OAuth integration.

function genericOAuthIntegration(
  config: GenericOAuthIntegrationConfig
): MCPIntegration;
export interface GenericOAuthIntegrationConfig {
  /** Integration unique identifier (must match the integration ID on the server) */
  id: string;

createSimpleIntegration()

Creates a simple integration without OAuth.

function createSimpleIntegration(config: {
  id: string;
  tools: string[];
  onInit?: (client: any) => Promise<void> | void;
  onAfterConnect?: (client: any) => Promise<void> | void;
  onDisconnect?: (client: any) => Promise<void> | void;
}): MCPIntegration;

Parameters:

  • id - Integration identifier
  • tools - Array of tool names to enable
  • onInit - Optional initialization hook
  • onAfterConnect - Optional post-connection hook
  • onDisconnect - Optional disconnect hook

Vercel AI SDK Integration

VercelAITool

Tool definition compatible with Vercel AI SDK v5:

export interface VercelAITool {
  description?: string;

VercelAIToolsOptions

Options for converting MCP tools to Vercel AI SDK format:

export interface VercelAIToolsOptions extends AIToolsOptions {
  /** User context for multi-tenant token storage */
  context?: MCPContext;

getVercelAITools()

Converts all enabled MCP tools to Vercel AI SDK format.

function getVercelAITools(
  client: MCPClient,
  options?: VercelAIToolsOptions
): Record<string, CoreTool>;

Parameters:

  • client - Connected MCP client
  • options - Optional configuration (see VercelAIToolsOptions above)

Returns:

  • Object mapping tool names to Vercel AI SDK tools

Example:

// Client-side
const tools = await getVercelAITools(mcpClient);
 
// Server-side with provider tokens
const tools = await getVercelAITools(serverClient, {
  providerTokens: { github: "ghp_...", gmail: "ya29..." },
});
 
const result = await generateText({
  model: openai("gpt-4"),
  prompt: "Create a GitHub issue",
  tools,
});

convertMCPToolsToVercelAI()

Alternative name for getVercelAITools().

function convertMCPToolsToVercelAI(client: MCPClient): Record<string, CoreTool>;

convertMCPToolToVercelAI()

Converts a single MCP tool to Vercel AI SDK format.

function convertMCPToolToVercelAI(tool: MCPTool, client: MCPClient): CoreTool;

Parameters:

  • tool - MCP tool definition
  • client - MCP client for execution

Returns:

  • Tool in Vercel AI SDK format

Example:

const tool = client.getTool("github_create_issue");
if (tool) {
  const vercelTool = convertMCPToolToVercelAI(tool, client);
}

Constants

Server URL

const MCP_SERVER_URL = "https://mcp.integrate.dev/api/v1/mcp";

Default Timeout

const DEFAULT_TIMEOUT = 30000; // 30 seconds

Error Types

The SDK provides specific error classes for different failure scenarios.

IntegrateSDKError

Base error class for all SDK errors.

class IntegrateSDKError extends Error {
  name: "IntegrateSDKError";
}

AuthenticationError

Error thrown when authentication fails or tokens are invalid.

class AuthenticationError extends IntegrateSDKError {
  name: "AuthenticationError";
  statusCode?: number; // HTTP status code (usually 401)
  provider?: string; // OAuth provider name
}

Example:

import { isAuthError, AuthenticationError } from "integrate-sdk";
 
try {
  await client.github.createIssue({
    owner: "user",
    repo: "repo",
    title: "Bug",
  });
} catch (error) {
  if (isAuthError(error)) {
    console.error(`Auth failed for ${error.provider}: ${error.message}`);
  }
}

TokenExpiredError

Error thrown when OAuth tokens have expired.

class TokenExpiredError extends AuthenticationError {
  name: "TokenExpiredError";
  provider?: string; // OAuth provider name
}

Example:

import { isTokenExpiredError } from "integrate-sdk";
 
try {
  await client.github.createIssue({
    owner: "user",
    repo: "repo",
    title: "Bug",
  });
} catch (error) {
  if (isTokenExpiredError(error)) {
    console.error(`Token expired for ${error.provider}`);
    // Trigger re-authentication
  }
}

AuthorizationError

Error thrown when access is forbidden due to insufficient permissions.

class AuthorizationError extends IntegrateSDKError {
  name: "AuthorizationError";
  statusCode?: number; // HTTP status code (usually 403)
  requiredScopes?: string[]; // Missing OAuth scopes
}

Example:

import { isAuthorizationError } from "integrate-sdk";
 
try {
  await client.github.createIssue({
    owner: "user",
    repo: "repo",
    title: "Bug",
  });
} catch (error) {
  if (isAuthorizationError(error)) {
    console.error("Insufficient permissions");
    if (error.requiredScopes) {
      console.error("Required scopes:", error.requiredScopes);
    }
  }
}

ConnectionError

Error thrown when a connection to the server fails.

class ConnectionError extends IntegrateSDKError {
  name: "ConnectionError";
  statusCode?: number; // HTTP status code
}

ToolCallError

Error thrown when a tool call fails.

class ToolCallError extends IntegrateSDKError {
  name: "ToolCallError";
  toolName: string; // Name of the tool that failed
  originalError?: unknown; // Original error from server
}

Error Helper Functions

Type guard functions for error handling:

// Check if error is any authentication error
function isAuthError(error: unknown): error is AuthenticationError;
 
// Check if error is specifically a token expired error
function isTokenExpiredError(error: unknown): error is TokenExpiredError;
 
// Check if error is an authorization error
function isAuthorizationError(error: unknown): error is AuthorizationError;

Example:

import {
  isAuthError,
  isTokenExpiredError,
  isAuthorizationError,
} from "integrate-sdk";
 
try {
  await client.github.createIssue({
    owner: "user",
    repo: "repo",
    title: "Bug",
  });
} catch (error) {
  if (isTokenExpiredError(error)) {
    // Handle token expiration
  } else if (isAuthError(error)) {
    // Handle other auth errors
  } else if (isAuthorizationError(error)) {
    // Handle permission errors
  } else {
    // Handle other errors
  }
}

parseServerError()

Utility function to parse server errors into appropriate error types.

function parseServerError(
  error: any,
  context?: { toolName?: string; provider?: string }
): IntegrateSDKError;

This function is used internally by the SDK but can be useful for custom error handling.

Triggers

The Trigger API allows you to schedule tool executions for one-time or recurring jobs.

client.trigger.create()

Create a new scheduled trigger.

async create(params: CreateTriggerParams): Promise<Trigger>

Parameters:

export interface CreateTriggerParams {
  /** Optional human-readable name */
  name?: string;

Returns:

The created trigger with generated ID and metadata.

Example:

// One-time trigger
const trigger = await client.trigger.create({
  name: "Send Email",
  toolName: "gmail_send_email",
  toolArguments: { to: "user@example.com", subject: "Hello" },
  schedule: { type: "once", runAt: new Date("2024-12-13T22:00:00Z") },
});
 
// Recurring trigger
const daily = await client.trigger.create({
  name: "Daily Report",
  toolName: "slack_send_message",
  toolArguments: { channel: "#team", text: "Daily report" },
  schedule: { type: "cron", expression: "0 9 * * *" },
});

client.trigger.list()

List triggers with optional filters.

async list(params?: ListTriggersParams): Promise<ListTriggersResponse>

Parameters:

export interface ListTriggersParams {
  /** Filter by status */
  status?: TriggerStatus;

Returns:

export interface ListTriggersResponse {
  /** Array of triggers */
  triggers: Trigger[];

Example:

// Get all triggers
const { triggers, total } = await client.trigger.list();
 
// Get active triggers
const active = await client.trigger.list({ status: "active", limit: 10 });
 
// Filter by tool name
const emailTriggers = await client.trigger.list({
  toolName: "gmail_send_email",
});

client.trigger.get()

Get a specific trigger by ID.

async get(triggerId: string): Promise<Trigger>

Parameters:

  • triggerId (string) - The trigger ID to retrieve

Returns:

The trigger details.

Example:

const trigger = await client.trigger.get("trig_abc123");
console.log(trigger.status); // 'active'
console.log(trigger.nextRunAt); // '2024-12-13T22:00:00Z'

client.trigger.update()

Update an existing trigger.

async update(triggerId: string, params: UpdateTriggerParams): Promise<Trigger>

Parameters:

  • triggerId (string) - The trigger ID to update
  • params (UpdateTriggerParams) - Partial trigger updates
export interface UpdateTriggerParams {
  /** Update trigger name */
  name?: string;

Returns:

The updated trigger.

Example:

// Update schedule
await client.trigger.update("trig_abc123", {
  schedule: { type: "cron", expression: "0 10 * * *" },
});
 
// Update arguments
await client.trigger.update("trig_abc123", {
  toolArguments: { channel: "#general" },
});

client.trigger.delete()

Delete a trigger permanently.

async delete(triggerId: string): Promise<void>

Parameters:

  • triggerId (string) - The trigger ID to delete

Example:

await client.trigger.delete("trig_abc123");

client.trigger.pause()

Pause a trigger (stop future executions without deleting).

async pause(triggerId: string): Promise<Trigger>

Parameters:

  • triggerId (string) - The trigger ID to pause

Returns:

The updated trigger with status 'paused'.

Example:

const paused = await client.trigger.pause("trig_abc123");
console.log(paused.status); // 'paused'

client.trigger.resume()

Resume a paused trigger.

async resume(triggerId: string): Promise<Trigger>

Parameters:

  • triggerId (string) - The trigger ID to resume

Returns:

The updated trigger with status 'active'.

Example:

const resumed = await client.trigger.resume("trig_abc123");
console.log(resumed.status); // 'active'

client.trigger.run()

Execute a trigger immediately, bypassing the schedule.

async run(triggerId: string): Promise<TriggerExecutionResult>

Parameters:

  • triggerId (string) - The trigger ID to execute

Returns:

export interface TriggerExecutionResult {
  /** Whether execution succeeded */
  success: boolean;

Example:

const result = await client.trigger.run("trig_abc123");
 
if (result.success) {
  console.log("Success:", result.result);
} else {
  console.error("Failed:", result.error);
}

Trigger Type

export interface Trigger {
  /** Unique trigger identifier */
  id: string;

TriggerSchedule Type

type TriggerSchedule =
  | { type: "once"; runAt: string | Date }
  | { type: "cron"; expression: string };

One-time schedule:

{ type: 'once', runAt: new Date('2024-12-13T22:00:00Z') }
{ type: 'once', runAt: '2024-12-13T22:00:00Z' }

Recurring schedule (cron):

{ type: 'cron', expression: '0 9 * * *' } // Daily at 9 AM
{ type: 'cron', expression: '0 9 * * 1-5' } // Weekdays at 9 AM
{ type: 'cron', expression: '0 */2 * * *' } // Every 2 hours

TriggerCallbacks

Database storage callbacks for server-side configuration:

export interface TriggerCallbacks {
  /**
   * Store a new trigger in your database
   * @param trigger - Trigger to create (includes generated ID)
   * @param context - Optional user context for multi-tenant support
   * @returns Created trigger with all fields populated
   */
  create: (trigger: Trigger, context?: MCPContext) => Promise<Trigger>;

Example:

import { createMCPServer } from "integrate-sdk/server";
 
export const { client } = createMCPServer({
  triggers: {
    create: async (trigger, context) => {
      return db.trigger.create({ data: trigger });
    },
    get: async (id, context) => {
      return db.trigger.findFirst({ where: { id } });
    },
    list: async (params, context) => {
      const triggers = await db.trigger.findMany({
        where: { status: params.status },
        take: params.limit,
      });
      return { triggers, total: triggers.length, hasMore: false };
    },
    update: async (id, updates, context) => {
      return db.trigger.update({ where: { id }, data: updates });
    },
    delete: async (id, context) => {
      await db.trigger.delete({ where: { id } });
    },
  },
});

Next Steps

  • Explore Advanced Usage for patterns and techniques
  • See example code in the repository