API Reference
Complete API reference for the Integrate SDK
API Reference
Complete reference documentation for the Integrate SDK.
createMCPClient
Creates a new MCP client instance.
function createMCPClient(config: MCPClientConfig): MCPClient;Parameters
interface MCPClientConfig {
plugins: MCPPlugin[]; // Array of plugins to enable
headers?: Record<string, string>; // Custom HTTP headers (optional)
timeout?: number; // Request timeout in ms (default: 30000)
clientInfo?: {
// Client identification (optional)
name: string;
version: string;
};
onReauthRequired?: ReauthHandler; // Re-authentication handler (optional)
maxReauthRetries?: number; // Max re-auth attempts (default: 1)
}
type ReauthHandler = (context: ReauthContext) => Promise<boolean> | boolean;
interface ReauthContext {
provider: string; // OAuth provider that needs re-authentication
error: AuthenticationError; // The error that triggered re-auth
toolName?: string; // Tool being called (if applicable)
}Returns
An MCPClient instance.
Example
const client = createMCPClient({
plugins: [
githubPlugin({
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();callTool()
Invokes a tool on the MCP server.
async callTool(name: string, args?: Record<string, any>): Promise<MCPToolCallResponse>Parameters:
name- Tool name (e.g., 'github_create_issue')args- Tool arguments as key-value pairs (optional)
Returns:
MCPToolCallResponse- Tool execution result
Example:
const result = await client.callTool("github_create_issue", {
repo: "owner/repo",
title: "Bug report",
body: "Description",
});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 plugins).
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 plugin.
getOAuthConfig(pluginId: string): OAuthConfig | undefinedParameters:
pluginId- Plugin 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 plugin IDs to OAuth configurations
Example:
const configs = client.getAllOAuthConfigs();
for (const [pluginId, config] of configs) {
console.log(`${pluginId}: ${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);
}Type Definitions
MCPTool
interface MCPTool {
name: string; // Tool name
description?: string; // Tool description
inputSchema: {
// JSON schema for parameters
type: "object";
properties?: Record<string, any>;
required?: string[];
};
}MCPToolCallResponse
interface MCPToolCallResponse {
content: Array<{
type: "text" | "image" | "resource";
text?: string;
data?: string;
mimeType?: string;
}>;
isError?: boolean;
}OAuthConfig
interface OAuthConfig {
provider: string; // OAuth provider name
clientId: string; // Client ID
clientSecret: string; // Client secret
scopes: string[]; // OAuth scopes
redirectUri?: string; // Redirect URI (optional)
}MCPPlugin
interface MCPPlugin {
id: string; // Unique identifier
tools: string[]; // Tool names to enable
oauth?: OAuthConfig; // OAuth config (optional)
onInit?: PluginHook; // Initialization hook (optional)
onBeforeConnect?: PluginHook; // Pre-connection hook (optional)
onAfterConnect?: PluginHook; // Post-connection hook (optional)
onDisconnect?: PluginHook; // Disconnect hook (optional)
}
type PluginHook = (client: MCPClient) => Promise<void> | void;Built-in Plugins
githubPlugin()
Creates a GitHub plugin.
function githubPlugin(config: GitHubPluginConfig): MCPPlugin;
interface GitHubPluginConfig {
clientId: string;
clientSecret: string;
scopes?: string[]; // Default: ['repo', 'user']
redirectUri?: string;
}gmailPlugin()
Creates a Gmail plugin.
function gmailPlugin(config: GmailPluginConfig): MCPPlugin;
interface GmailPluginConfig {
clientId: string;
clientSecret: string;
scopes?: string[]; // Default: common Gmail scopes
redirectUri?: string;
}genericOAuthPlugin()
Creates a generic OAuth plugin.
function genericOAuthPlugin(config: GenericOAuthPluginConfig): MCPPlugin;
interface GenericOAuthPluginConfig {
id: string; // Plugin identifier
provider: string; // OAuth provider name
clientId: string;
clientSecret: string;
scopes: string[];
tools: string[]; // Tool names to enable
redirectUri?: string;
}createSimplePlugin()
Creates a simple plugin without OAuth.
function createSimplePlugin(config: SimplePluginConfig): MCPPlugin;
interface SimplePluginConfig {
id: string; // Plugin identifier
tools: string[]; // Tool names to enable
onInit?: PluginHook;
onBeforeConnect?: PluginHook;
onAfterConnect?: PluginHook;
onDisconnect?: PluginHook;
}Vercel AI SDK Integration
getVercelAITools()
Converts all enabled MCP tools to Vercel AI SDK format.
function getVercelAITools(client: MCPClient): Record<string, CoreTool>;Parameters:
client- Connected MCP client
Returns:
- Object mapping tool names to Vercel AI SDK tools
Example:
const tools = getVercelAITools(mcpClient);
const result = await generateText({
model: openai("gpt-5"),
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.callTool("github_create_issue", { ... });
} 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.callTool("github_create_issue", { ... });
} 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.callTool("github_create_issue", { ... });
} 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.callTool("github_create_issue", { ... });
} 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