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 moreGmail Integration Methods:
client.gmail.sendEmail(params);
client.gmail.listEmails(params);
client.gmail.searchEmails(params);
client.gmail.createLabel(params);
// ... and moreServer Methods:
client.server.listToolsByIntegration(params);
client.server.listAllProviders();
client.server.listConfiguredIntegrations();
// ... other server-level toolsExample:
// 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 | undefinedParameters:
name- Tool name
Returns:
MCPToolorundefinedif 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
MCPToolobjects
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
MCPToolobjects
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 | undefinedParameters:
integrationId- Integration identifier
Returns:
OAuthConfigorundefinedif 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): () => voidParameters:
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(): booleanReturns:
trueif connected,falseotherwise
Example:
if (client.isConnected()) {
console.log("Client is connected");
}isInitialized()
Checks if the client is initialized.
isInitialized(): booleanReturns:
trueif initialized,falseotherwise
Example:
if (client.isInitialized()) {
console.log("Client is initialized");
}getAuthState()
Gets authentication state for a specific provider.
getAuthState(provider: string): { authenticated: boolean; lastError?: AuthenticationError } | undefinedParameters:
provider- Provider identifier (e.g., 'github', 'gmail')
Returns:
- Authentication state object or
undefinedif 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): booleanParameters:
provider- Provider identifier
Returns:
trueif authenticated,falseotherwise
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:
trueif re-authentication succeeded,falseotherwise
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 on this SDK client. This is a local-only operation that doesn't make any server calls.
async listConfiguredIntegrations(): Promise<{
integrations: ConfiguredIntegration[];
}>Returns:
- Object with
integrationsarray containing:id(string) - Integration identifiername(string) - Integration display nametools(readonly string[]) - Array of tool names available for this integrationhasOAuth(boolean) - Whether the integration requires OAuthscopes(readonly string[] | undefined) - OAuth scopes if applicableprovider(string | undefined) - OAuth provider name if applicable
Example:
// Get all configured integrations
const { integrations } = await client.server.listConfiguredIntegrations();
console.log(`Configured ${integrations.length} integrations:`);
integrations.forEach((integration) => {
console.log(`- ${integration.name} (${integration.id})`);
console.log(` Tools: ${integration.tools.length}`);
console.log(` OAuth: ${integration.hasOAuth ? 'Yes' : 'No'}`);
if (integration.scopes) {
console.log(` Scopes: ${integration.scopes.join(', ')}`);
}
});Note: This method returns only the integrations configured on your local client instance. It does not query the MCP server, making it fast and suitable for checking client configuration.
Type Definitions
MCPTool
Prop
Type
MCPToolCallResponse
Prop
Type
MCPToolCallParams
Prop
Type
OAuthConfig
Prop
Type
MCPIntegration
Prop
Type
ConfiguredIntegration
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 identifiertools- Array of tool names to enableonInit- Optional initialization hookonAfterConnect- Optional post-connection hookonDisconnect- 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 clientoptions- 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 definitionclient- 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 secondsError 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:
Prop
Type
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:
Prop
Type
Returns:
Prop
Type
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 updateparams(UpdateTriggerParams) - Partial trigger updates
Prop
Type
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:
Prop
Type
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
Prop
Type
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 hoursTriggerCallbacks
Database storage callbacks for server-side configuration:
Prop
Type
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
- Check Architecture to understand the internals
- See example code in the repository