Log inStart Free Trial
easyCoexistence Official APIs

Use social media tools in the Vercel AI SDK: Instagram, TikTok and more

The Vercel AI SDK gets social media tools for Instagram, TikTok, Facebook, WhatsApp and more channels from easyCoexistence's MCP server. createMCPClient, from the @ai-sdk/mcp package, opens an HTTP connection to https://easycoexistence.com/api/mcp, an OAuthClientProvider you write keeps the sign-in, and the client's tools() go into generateText or streamText to publish, schedule, reply to comments and DMs and read insights through each network's official API.

auth()

The @ai-sdk/mcp function that finishes an OAuth callback from serverUrl and the authorizationCode, plus callbackState and callbackIssuer when present.

isStepCount(1)

generateText's default stopWhen, so the model only reads a tool's result when stopWhen allows more steps.

HTTP

The MCP transport the AI SDK recommends for production; its stdio transport is meant for local servers only.

1 hour

The life of an easyCoexistence MCP access token; its refresh token lasts 60 days and is replaced at each refresh.

1,000 bytes

The most text one Instagram DM carries, measured in UTF-8, so accents and emoji take more of it.

How does the AI SDK sign in to easyCoexistence?

Through an OAuthClientProvider you implement over your own storage, which the AI SDK's auth() function drives. The first call registers your app with easyCoexistence as a public client, saves the PKCE verifier and hands you the consent URL through redirectToAuthorization; it returns REDIRECT, and your route sends the user there. easyCoexistence then redirects to your callback with a code, and a second auth() call with authorizationCode trades it for tokens. Once tokens are stored, auth() uses the refresh token for a new pair instead of sending the user back. Keep redirectUrl and the registered redirect_uris identical, since easyCoexistence matches them exactly.

An OAuthClientProvider over your database, with the two routes it needs
import { auth, type OAuthClientProvider } from "@ai-sdk/mcp";

export const MCP_URL = "https://easycoexistence.com/api/mcp";
const CALLBACK = "https://app.example.com/api/easycoexistence/callback";

// db is your own key-value store (Postgres, Redis, Vercel KV); one set of keys per user
export function easyAuth(userId: string): OAuthClientProvider {
  const k = (name: string) => "easycoexistence:" + userId + ":" + name;
  return {
    get redirectUrl() { return CALLBACK; },
    get clientMetadata() {
      return {
        client_name: "Acme app", // shown on easyCoexistence's consent screen
        redirect_uris: [CALLBACK],
        grant_types: ["authorization_code", "refresh_token"],
        response_types: ["code"],
        token_endpoint_auth_method: "none", // easyCoexistence registers public clients
      };
    },
    clientInformation: () => db.get(k("client")),
    saveClientInformation: (info) => db.set(k("client"), info),
    isClientInformationDynamicallyRegistered: async () => Boolean(await db.get(k("client"))),
    tokens: () => db.get(k("tokens")),
    saveTokens: (tokens) => db.set(k("tokens"), tokens),
    saveCodeVerifier: (verifier) => db.set(k("verifier"), verifier),
    codeVerifier: () => db.get(k("verifier")),
    redirectToAuthorization: (url) => db.set(k("sign-in"), url.href),
  };
}

// GET /api/easycoexistence/connect: send the user to the consent screen
export async function connect(userId: string) {
  const result = await auth(easyAuth(userId), { serverUrl: MCP_URL });
  if (result === "AUTHORIZED") return new Response("Already connected");
  return Response.redirect(await db.get("easycoexistence:" + userId + ":sign-in"));
}

// GET /api/easycoexistence/callback: trade the code for tokens
export async function callback(req: Request, userId: string) {
  const code = new URL(req.url).searchParams.get("code");
  if (!code) return new Response("Sign-in was cancelled", { status: 400 });
  await auth(easyAuth(userId), { serverUrl: MCP_URL, authorizationCode: code });
  return Response.redirect("https://app.example.com/settings");
}

How do the tools reach generateText?

From createMCPClient with the HTTP transport, the easyCoexistence URL and the provider. tools() returns the server's tools as AI SDK tools; keep the ones the job needs by name and pass them to generateText or streamText. Set stopWhen with isStepCount, because by default the call stops after one step and the model never reads what reply_to_comment returned. Put the network rules in instructions, the parameter the current reference uses for the model's behavior. Close the client in a finally block, or in streamText's onEnd callback, so no connection is left open.

Reply to one forwarded comment or DM with a filtered set of tools
import { createMCPClient } from "@ai-sdk/mcp";
import { generateText, isStepCount, type LanguageModel } from "ai";
import { easyAuth, MCP_URL } from "./easycoexistence-auth";

const REPLY_TOOLS = new Set(["list_social_comments", "reply_to_comment", "hide_comment", "send_social_dm"]);

export async function replyToEvent(userId: string, model: LanguageModel, event: unknown) {
  const mcp = await createMCPClient({
    transport: { type: "http", url: MCP_URL, authProvider: easyAuth(userId) },
  });
  try {
    const tools = Object.fromEntries(
      Object.entries(await mcp.tools()).filter(([name]) => REPLY_TOOLS.has(name)),
    );
    const { text } = await generateText({
      model,
      tools,
      stopWhen: isStepCount(4),
      instructions:
        "Reply to comments and DMs for Acme on the event's account_id. TikTok replies are public " +
        "and need the video ID as post_id. Instagram DMs only go to people who wrote in the last 24 hours.",
      prompt: JSON.stringify(event),
    });
    return text;
  } finally {
    await mcp.close();
  }
}

Where should the tokens live on a serverless host?

Anywhere that outlives one invocation: a database row, Redis or a key-value store, keyed by the user of your app the tokens belong to. A function on Vercel or another serverless platform starts with nothing in memory, so a provider that keeps tokens in a variable sends the user back to the consent screen after a cold start. Access tokens last an hour and refresh tokens 60 days, with a new refresh token each time one is used, so an app that calls the tools at least once in 60 days stays signed in. Keep the client registration beside the tokens, since the provider reads both on each connection.

How do comments and DMs reach the app?

As signed POSTs to a route handler, which set_social_webhook_destination registers for an account and which then receives Instagram and Facebook comments, mentions and DMs, and TikTok comments. Each body holds platform, account_id, external_id and entry, the network's event as it was sent. Read the body as text, check X-EC-Signature against it with the account's signing secret, and respond quickly: easyCoexistence gives the route 8 seconds and sends each event once, with no retry. Put the event on a queue and let a worker call replyToEvent with it, so the model's time never counts against the 8 seconds.

What does each network let the model do?

As much as the account's API allows, which the instructions should spell out:

  • Instagram: posts, Reels and Stories with JPEG images; DM replies only to people who wrote in the last 24 hours, in at most 1,000 bytes.
  • Facebook: Page posts, comment replies and Messenger replies inside the same 24 hours.
  • TikTok: videos and photo posts; comment replies always public, with the video's ID as post_id, and no DMs.
  • WhatsApp: send_message within 24 hours of the customer's last message, send_template for anyone else.
  • YouTube and LinkedIn: uploads and posts when a user asks, comment replies and analytics; neither forwards events, so the app reads new comments on a schedule.

Common mistakes

  • Leaving stopWhen at its default. generateText stops after the first step, so the model calls reply_to_comment and never learns whether the reply went out; allow a few steps with isStepCount.
  • Keeping tokens in a module-level variable on a serverless host. The next cold start has none, and the user lands on the consent screen again; save them where tokens() and saveTokens() reach a database.
  • Registering one redirect URL and sending another. easyCoexistence checks redirect_uri against the registration exactly, so a trailing slash or a different path ends the sign-in on an error page.
  • Replying to the account's own activity. Instagram sends the account's DMs back as echoes and its public replies return as comments, so skip both before the prompt reaches the model.
Doing this with EasyCoexistence

easyCoexistence gives the agents you build with the Vercel AI SDK reach to customers on WhatsApp, Instagram, Facebook, TikTok, YouTube, LinkedIn and more channels, each through its official API: MCP tools behind an OAuth sign-in, signed events for comments and DMs, and a posting queue up to 90 days ahead, with every connection monitored 24/7. US$ 9 to US$ 0.75 per connection per month, falling as you add connections, with the first 3 days free.

easyCoexistence is a multichannel API and MCP server that connects AI agents such as Claude and ChatGPT to WhatsApp, Instagram, TikTok, Facebook and more. On WhatsApp it uses Coexistence: the business keeps using its number in the WhatsApp Business app while the AI works through Meta's official API.

Frequently asked questions

Does this need Next.js or Vercel hosting?

No. The AI SDK runs in Node.js, so any host that serves an HTTPS route works, and the MCP client only needs outbound HTTPS to easycoexistence.com.

Can a chat interface stream the tool calls?

Yes. Pass the same tools to streamText and close the MCP client in its onEnd callback, as the AI SDK documents for streamed responses.

Can the same app reply to WhatsApp messages?

Yes. The number's tools come through the same client: list_numbers for the connection_id, then send_message within 24 hours of the customer's last message. The AI SDK guide for WhatsApp covers receiving them.

How much does easyCoexistence cost for an AI SDK app?

US$ 9 to US$ 0.75 per connection per month, falling as you add connections, the same on each network. The MCP server and the Partner API are part of it, and the first 3 days are free.

Keep reading

Connect your first channel in two minutes.

No platform reviews to wait for. Connect WhatsApp, Instagram, TikTok or another channel, then ask your AI to post, reply or report, and watch it work.

  • 3 days free
  • Cancel any time
  • Official APIs only
  • Monitored 24/7

Verified on