Integrate
Getting started

Advanced Usage

Advanced configuration options and patterns for power users

This guide covers advanced configuration options for power users who need custom client configuration and fine-grained control over connection behavior, OAuth flows, error handling, and more.

Custom Client Configuration

For advanced use cases, you can create a custom configured client instead of using the default client:

// lib/integrate-client.ts
import { createMCPClient, githubIntegration } from "integrate-sdk";

export const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
});

Then import and use your custom client:

import { client } from "@/lib/integrate-client";

await client.authorize("github");

Connection Modes

Control when and how the client connects to the MCP server.

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  connectionMode: "lazy",
});

await client.github.listOwnRepos({});

const eagerClient = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  connectionMode: "eager",
});

const manualClient = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  connectionMode: "manual",
});

await manualClient.connect();
await manualClient.github.listOwnRepos({});
await manualClient.disconnect();

When to Use Each Mode

  • lazy (default): Best for most use cases - connects automatically when needed
  • eager: When you want to pre-connect and cache the connection, or validate credentials early
  • manual: When you need precise control over connection lifecycle (testing, connection pooling)

Singleton Pattern

By default, createMCPClient returns cached instances to improve performance and reduce connections.

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client1 = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  singleton: true,
});

const client2 = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  singleton: true,
});

const uniqueClient = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  singleton: false,
});

Clearing the Cache

import { clearClientCache } from "integrate-sdk";

// Clear all cached clients and disconnect them
await clearClientCache();

Auto-Cleanup

Control whether clients automatically disconnect on process exit.

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  autoCleanup: true,
});

const manualClient = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  autoCleanup: false,
});

await manualClient.disconnect();

Re-Authentication Handling

Handle expired or invalid OAuth tokens automatically.

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  onReauthRequired: async (context) => {
    console.log(`Re-auth needed for ${context.provider}`);
    console.log(`Error: ${context.error.message}`);
    console.log(`Tool: ${context.toolName}`);
    try {
      await client.authorize(context.provider);
      return true;
    } catch (error) {
      console.error("Re-auth failed:", error);
      return false;
    }
  },
  maxReauthRetries: 1,
});

try {
  await client.github.createIssue({
    owner: "owner",
    repo: "repo",
    title: "Test issue",
  });
} catch (error) {
  console.error("Failed:", error);
}

OAuth Flow Configuration

Customize the OAuth authorization experience.

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  oauthFlow: {
    mode: "popup",
    popupOptions: {
      width: 600,
      height: 700,
    },
    onAuthCallback: async (provider, code, state) => {
      console.log(`Received callback for ${provider}`);
    },
  },
});

Popup Mode:

  • Opens OAuth in a new window
  • User stays on current page
  • Better for single-page apps
  • Blocked by some browsers

Redirect Mode (default):

  • Full page redirect to OAuth provider
  • More reliable, works everywhere
  • Preserves URL with returnUrl

OAuth Configuration

Fine-tune OAuth behavior and URLs.

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  oauthApiBase: "/api/integrate/oauth",
  redirectUri: "https://myapp.com/api/integrate/oauth/callback",
  autoHandleOAuthCallback: true,
  sessionToken: "existing-session-token",
});

OAuth Redirect URI Auto-Detection

Client-side:

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
});

Server-side:

import { createMCPServer, githubIntegration } from "integrate-sdk/server";

const { client } = createMCPServer({
  apiKey: process.env.INTEGRATE_API_KEY,
  integrations: [
    githubIntegration({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
      scopes: ["repo", "user"],
    }),
  ],
});

const { client: explicitClient } = createMCPServer({
  apiKey: process.env.INTEGRATE_API_KEY,
  integrations: [
    githubIntegration({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
      scopes: ["repo", "user"],
    }),
  ],
  redirectUri: process.env.OAUTH_REDIRECT_URI,
});

Client Information

Customize the client identity sent to the MCP server.

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  clientInfo: {
    name: "my-app",
    version: "1.2.3",
  },
});

HTTP Configuration

Configure HTTP transport settings.

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
  headers: {
    "X-Custom-Header": "value",
    "X-App-Version": "1.0.0",
  },
  timeout: 60000,
});

Server-Side Configuration

createMCPServer supports the same options as createMCPClient, plus server-specific features.

import { createMCPServer, githubIntegration } from "integrate-sdk/server";

export const { client, POST, GET } = createMCPServer({
  apiKey: process.env.INTEGRATE_API_KEY,
  integrations: [
    githubIntegration({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
      scopes: ["repo", "user"],
    }),
  ],
  connectionMode: "lazy",
  singleton: true,
  autoCleanup: true,
  timeout: 30000,
  redirectUri: process.env.OAUTH_REDIRECT_URI,
});

export { POST, GET };

Event Listeners

Listen to OAuth events for custom logic.

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
});

client.on("auth:started", ({ provider }) => {
  console.log(`Starting OAuth for ${provider}`);
});

client.on("auth:complete", ({ provider, accessToken, expiresAt }) => {
  console.log(`${provider} authorized until ${expiresAt}`);
});

client.on("auth:error", ({ provider, error }) => {
  console.error(`Auth error for ${provider}:`, error.message);
});

client.on("auth:disconnect", ({ provider }) => {
  console.log(`${provider} disconnected`);
});

client.on("auth:logout", () => {
  console.log("User logged out from all services");
});

const handler = ({ provider }) => console.log(provider);
client.on("auth:complete", handler);
client.off("auth:complete", handler);

Provider Token Management

Work with provider tokens directly.

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
});

const githubToken = client.getProviderToken("github");
console.log(githubToken.accessToken);
console.log(githubToken.expiresAt);

client.setProviderToken("github", {
  accessToken: "ghp_...",
  tokenType: "Bearer",
  expiresIn: 3600,
});

const allTokens = client.getAllProviderTokens();

await fetch("/api/ai", {
  method: "POST",
  headers: {
    "x-integrate-tokens": JSON.stringify(allTokens),
  },
  body: JSON.stringify({ prompt: "Create an issue" }),
});

Checking Authorization

Multiple ways to check if providers are authorized.

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
});

const isAuthorized = await client.isAuthorized("github");

const authorized = await client.authorizedProviders();
console.log(authorized);

const status = await client.getAuthorizationStatus("github");
console.log(status.authorized);
console.log(status.scopes);
console.log(status.expiresAt);

Disconnect and Logout

Manage user sessions.

import { createMCPClient, githubIntegration } from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
  ],
});

await client.disconnectProvider("github");

const isAuthorized = await client.isAuthorized("github");

await client.logout();

await client.authorize("github");
await client.authorize("gmail");

Complete Example

Here's a comprehensive example using multiple advanced features:

import {
  createMCPClient,
  githubIntegration,
  gmailIntegration,
} from "integrate-sdk";

const client = createMCPClient({
  integrations: [
    githubIntegration({
      scopes: ["repo", "user"],
    }),
    gmailIntegration(),
  ],
  connectionMode: "lazy",
  singleton: true,
  autoCleanup: true,
  oauthFlow: {
    mode: "popup",
    popupOptions: { width: 600, height: 700 },
  },
  oauthApiBase: "/api/integrate/oauth",
  autoHandleOAuthCallback: true,
  onReauthRequired: async ({ provider, error }) => {
    console.log(`Re-auth needed for ${provider}: ${error.message}`);
    await client.authorize(provider);
    return true;
  },
  maxReauthRetries: 2,
  timeout: 60000,
  headers: {
    "X-App-Version": "1.0.0",
  },
  clientInfo: {
    name: "my-awesome-app",
    version: "1.0.0",
  },
});

client.on("auth:complete", ({ provider }) => {
  console.log(`✅ ${provider} connected`);
});

client.on("auth:error", ({ provider, error }) => {
  console.error(`❌ ${provider} error:`, error);
});

try {
  await client.github.createIssue({
    owner: "owner",
    repo: "repo",
    title: "Test issue",
  });
} catch (error) {
  console.error("Failed to create issue:", error);
}

Next Steps