Integrate
Reference

Options

Complete API reference for the Integrate SDK

createMCPClient

Creates a new MCP client instance.

function createMCPClient(config: MCPClientConfig): MCPClient;

Parameters

Prop

Type

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);
// ... 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);
}

Type Definitions

MCPTool

Prop

Type

MCPToolCallResponse

Prop

Type

MCPToolCallParams

Prop

Type

OAuthConfig

Prop

Type

MCPIntegration

Prop

Type

ReauthContext

Prop

Type

OAuth Types

PopupOptions

Prop

Type

OAuthFlowConfig

Prop

Type

AuthStatus

Prop

Type

ProviderTokenData

Prop

Type

OAuthCallbackParams

Prop

Type

OAuth Event Types

AuthStartedEvent

Prop

Type

AuthCompleteEvent

Prop

Type

AuthErrorEvent

Prop

Type

AuthLogoutEvent

Prop

Type

AuthDisconnectEvent

Prop

Type

Built-in Integrations

githubIntegration()

Creates a GitHub integration.

function githubIntegration(config: GitHubIntegrationConfig): MCPIntegration;

Prop

Type

gmailIntegration()

Creates a Gmail integration.

function gmailIntegration(config: GmailIntegrationConfig): MCPIntegration;

Prop

Type

genericOAuthIntegration()

Creates a generic OAuth integration.

function genericOAuthIntegration(
  config: GenericOAuthIntegrationConfig
): MCPIntegration;

Prop

Type

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:

Prop

Type

VercelAIToolsOptions

Options for converting MCP tools to Vercel AI SDK format:

Prop

Type

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.

Next Steps

  • Explore Advanced Usage for patterns and techniques
  • Check Architecture to understand the internals
  • See example code in the repository