How to integrate Twitter MCP with Vercel AI SDK

Framework Integration Gradient
Twitter Logo
Vercel AI SDK Logo
divider

Introduction

This guide walks you through connecting Twitter to Vercel AI SDK using the Composio tool router. By the end, you'll have a working Twitter agent that can post a tweet with latest blog link, add user to my conference list, retrieve my most recent bookmarked tweets, start a group dm with collaborators through natural language commands.

This guide will help you understand how to give your Vercel AI SDK agent real control over a Twitter account through Composio's Twitter MCP server.

Before we dive in, let's take a quick look at the key ideas and tools involved.

TL;DR

Here's what you'll learn:
  • How to set up and configure a Vercel AI SDK agent with Twitter integration
  • Using Composio's Tool Router to dynamically load and access Twitter tools
  • Creating an MCP client connection using HTTP transport
  • Building an interactive CLI chat interface with conversation history management
  • Handling tool calls and results within the Vercel AI SDK framework

What is Vercel AI SDK?

The Vercel AI SDK is a TypeScript library for building AI-powered applications. It provides tools for creating agents that can use external services and maintain conversation state.

Key features include:

  • streamText: Core function for streaming responses with real-time tool support
  • MCP Client: Built-in support for Model Context Protocol
  • Step Counting: Control multi-step tool execution
  • OpenAI Provider: Native integration with OpenAI models

What is the Twitter MCP server, and what's possible with it?

The Twitter MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Twitter (now X) account. It provides structured and secure access to your social media presence, so your agent can perform actions like posting tweets, managing lists, handling bookmarks, and starting group DMs on your behalf.

  • Automated tweet posting and management: Let your agent compose and publish tweets, including text, media, polls, or quote tweets, directly to your timeline.
  • List creation and member management: Have your agent create new Twitter lists, add or remove users, fetch list members, or delete lists as needed.
  • Bookmark handling and retrieval: Easily get your bookmarked tweets or add posts to your bookmarks for quick access later, all through your agent.
  • Direct and group message automation: Enable your agent to create group DMs, send initial messages, or delete specific direct messages securely and efficiently.
  • Compliance and content moderation: Use your agent to set up compliance jobs, check the status of tweets or user IDs, and help manage your account’s integrity.

Supported Tools & Triggers

Tools
Add a list memberAdds a user to a specified twitter list; the list must be owned by the authenticated user.
Add post to bookmarksAdds a specified, existing, and accessible tweet to a user's bookmarks, with success indicated by the 'bookmarked' field in the response.
Get bookmarks by userRetrieves tweets bookmarked by the authenticated user, where the provided user id must match the authenticated user's id.
Create group DM conversationCreates a new group direct message (dm) conversation on twitter with specified participant ids and an initial message, which can include text and media attachments.
Create compliance jobCreates a new compliance job to check the status of tweet or user ids; upload ids as a plain text file (one id per line) to the `upload url` received in the response.
Create a listCreates a new, empty list on x (formerly twitter), for which the provided name must be unique for the authenticated user; accounts are added separately.
Create a postCreates a tweet on twitter; `text` is required unless `card uri`, `media media ids`, `poll options`, or `quote tweet id` is provided.
Delete direct messagePermanently deletes a specific twitter direct message (dm) event using its `event id` if the authenticated user sent it; this action is irreversible and does not delete entire conversations.
Delete listPermanently deletes a specified twitter list using its id, which must be owned by the authenticated user; this action is irreversible and the list must already exist.
Fetch list members by idFetches members of a specific twitter list, identified by its unique id.
Fetch space ticket buyers listRetrieves a list of users who purchased tickets for a specific, valid, and ticketed twitter space.
Follow a listAllows the authenticated user (`id`) to follow a specific twitter list (`list id`) they are permitted to access, subscribing them to the list's timeline; this does not automatically follow individual list members.
Get followers by user idRetrieves a list of users who follow a specified public twitter user id.
Get following by user IDRetrieves users followed by a specific twitter user, allowing pagination and customization of returned user and tweet data fields via expansions.
Follow a userAllows an authenticated user (path `id`) to follow another user (`target user id`), which results in a pending request if the target user's tweets are protected.
Search full archive of tweetsSearches the full archive of public tweets from march 2006 onwards; use 'start time' and 'end time' together for a defined time window.
Get full archive search countsReturns a count of tweets from the full archive that match a specified query, aggregated by day, hour, or minute; `start time` must be before `end time` if both are provided, and `since id`/`until id` cannot be used with `start time`/`end time`.
Get a user's list membershipsRetrieves all twitter lists a specified user is a member of, including public lists and private lists the authenticated user is authorized to view.
Get a user's owned listsCall this action to retrieve lists created (owned) by a specific twitter user, not lists they follow or are subscribed to.
Get a user's pinned listsRetrieves the lists a specific, existing twitter user has pinned to their profile to highlight them.
Get users blocked by user IDRetrieves user objects for accounts blocked by the specified user id; this is a read-only view of a user's block list.
Get DM events by IDFetches a specific direct message (dm) event by its unique id, allowing optional expansion of related data like users or tweets; ensure the `event id` refers to an existing dm event accessible to the authenticated user.
Get DM events for a DM conversationFetches direct message (dm) events for a one-on-one conversation with a specified participant id, ordered chronologically newest to oldest; does not support group dms.
Get list followersFetches a list of users who follow a specific twitter list, identified by its id; ensure the authenticated user has access if the list is private.
Get muted usersReturns user objects muted by the x user identified by the `id` path parameter.
Get post retweetersRetrieves users who publicly retweeted a specified public post id, excluding quote tweets and retweets from private accounts.
Get recent direct message eventsReturns recent direct message events for the authenticated user, such as new messages or changes in conversation participants.
Get user's followed listsReturns metadata (not tweets) for lists a specific twitter user follows, optionally including expanded owner details.
Set reply visibilityHides or unhides an existing reply tweet.
Lookup list by IDReturns metadata for a specific twitter list, identified by its id; does not return list members but can expand the owner's user object via the `expansions` parameter.
List post likersRetrieves users who have liked the post (tweet) identified by the provided id.
List posts timeline by list IDFetches the most recent tweets posted by members of a specified twitter list.
Mute user by IDMutes a target user on behalf of an authenticated user, preventing the target's tweets and retweets from appearing in the authenticated user's home timeline without notifying the target.
Pin a listPins a specified list to the authenticated user's profile, provided the list exists, the user has access rights, and the pin limit (typically 5 lists) is not exceeded.
Delete tweetIrreversibly deletes a specific tweet by its id; the tweet may persist in third-party caches after deletion.
Look up post by idFetches comprehensive details for a single tweet by its unique id, provided the tweet exists and is accessible.
Get tweets by IDsRetrieves detailed information for one or more posts (tweets) identified by their unique ids, allowing selection of specific fields and expansions.
Get tweets label streamEstablishes a persistent stream of real-time events for when tweet labels are applied or removed, offering insights into content categorization.
Fetch tweet usage dataFetches tweet usage statistics for a project (e.
Search recent tweetsSearches tweets from the last 7 days matching a query (using x's search syntax), ideal for real-time analysis, trend monitoring, or retrieving posts from specific users (e.
Fetch recent tweet countsRetrieves the count of tweets matching a specified search query within the last 7 days, aggregated by 'minute', 'hour', or 'day'.
Remove a bookmarked postRemoves a tweet, specified by `tweet id`, from the authenticated user's bookmarks; the tweet must have been previously bookmarked by the user for the action to have an effect.
Remove a list memberRemoves a user from a twitter list; the response `is member` field will be `false` if removal was successful or the user was not a member, and the updated list of members is not returned.
Retrieve compliance job by idRetrieves status, download/upload urls, and other details for an existing twitter compliance job specified by its unique id.
Retrieve compliance jobsReturns a list of recent compliance jobs, filtered by type (tweets or users) and optionally by status.
Retrieve DM conversation eventsRetrieves direct message (dm) events for a specific conversation id on twitter, useful for analyzing messages and participant activities.
Retrieve posts from a spaceRetrieves tweets from a specified twitter space id; the space must be accessible and results are batched (not streamed).
Retrieve posts that quote a postRetrieves tweets that quote a specified tweet, requiring a valid tweet id.
Retrieve retweets of a postRetrieves tweets that retweeted a specified public or authenticated-user-accessible tweet id, optionally customizing the response with fields and expansions.
Retrieve liked tweets by user IDRetrieves tweets liked by a specified twitter user, provided their liked tweets are public or accessible.
Fetch OpenAPI specificationFetches the openapi specification (json) for twitter's api v2, used to programmatically understand the api's structure for developing client libraries or tools.
Retweet postRetweets a tweet (`tweet id`) for a given user (`id`), provided the tweet is public (or user follows if protected), not already retweeted by the user, and its author has not blocked the user.
Search for spacesSearches for twitter spaces by a textual query, optionally filtering by state (live, scheduled, all) to discover audio conversations.
Send a new message to a DM conversationSends a message, with optional text and/or media attachments (using pre-uploaded `media id`s), to a specified twitter direct message conversation.
Send a new message to a userSends a new direct message with text and/or media (media id for attachments must be pre-uploaded) to a specified twitter user; this creates a new dm and does not modify existing messages.
Look up space by IDRetrieves details for a twitter space by its id, allowing for customization and expansion of related data, provided the space id is valid and accessible.
Get spaces by creator IDsRetrieves twitter spaces created by a list of specified user ids, with options to customize returned data fields.
Get space information by IDsFetches detailed information for one or more twitter spaces (live, scheduled, or ended) by their unique ids; at least one space id must be provided.
Unfollow a listEnables a user (via `id`) to unfollow a specific twitter list (via `list id`), which removes its tweets from their timeline and stops related notifications; the action reports `following: false` on success, even if the user was not initially following the list.
Unfollow userAllows the authenticated `source user id` to unfollow an existing twitter user (`target user id`), which removes the follow relationship.
Unlike postAllows an authenticated user (`id`) to remove their like from a specific post (`tweet id`); the action is idempotent and completes successfully even if the post was not liked.
Unmute a user by user IDUnmutes a `target user id` for the `source user id` (authenticated user), allowing the source user to see tweets and notifications from the target user again.
Unpin a listUnpins a list (specified by list id) from a user's profile (specified by id), provided the list is currently pinned by that user.
Unretweet postRemoves a user's retweet of a specified post, if the user had previously retweeted it.
Update list attributesUpdates an existing twitter list's name, description, or privacy status, requiring the list id and at least one mutable property.
Get user reverse chronological timelineRetrieves the home timeline/feed for a specified twitter user, showing tweets from accounts they follow - not their own posts - in reverse chronological order; useful for displaying their personalized feed without algorithmic sorting.
Like a tweetAllows the authenticated user (`id`) to like a specific, accessible tweet (`tweet id`), provided neither user has blocked the other and the authenticated user is not restricted from liking.
Look up user by IDRetrieves detailed public information for a twitter user by their id, optionally expanding related data (e.
Look up users by IDsRetrieves detailed information for specified x (formerly twitter) user ids, optionally customizing returned fields and expanding related entities.
Look up user by usernameFetches public profile information for a valid and existing twitter user by their username, optionally expanding related data like pinned tweets; results may be limited for protected profiles not followed by the authenticated user.
Look up users by usernameRetrieves detailed information for 1 to 100 twitter users by their usernames (each 1-15 alphanumeric characters/underscores), allowing customizable user/tweet fields and expansion of related data like pinned tweets.
Get authenticated userReturns profile information for the currently authenticated x user, customizable via request fields.

What is the Composio tool router, and how does it fit here?

What is Tool Router?

Composio's Tool Router helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Tool Router

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Tool Router works

The Tool Router follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

Prerequisites

Before you begin, make sure you have:
  • Node.js and npm installed
  • A Composio account with API key
  • An OpenAI API key

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key. You'll need credits to use the models, or you can connect to another model provider.
  • Keep the API key safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Navigate to your API settings and generate a new API key.
  • Store this key securely as you'll need it for authentication.

Install required dependencies

bash
npm install @ai-sdk/openai @ai-sdk/mcp @composio/core ai dotenv

First, install the necessary packages for your project.

What you're installing:

  • @ai-sdk/openai: Vercel AI SDK's OpenAI provider
  • @ai-sdk/mcp: MCP client for Vercel AI SDK
  • @composio/core: Composio SDK for tool integration
  • ai: Core Vercel AI SDK
  • dotenv: Environment variable management

Set up environment variables

bash
OPENAI_API_KEY=your_openai_api_key_here
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here

Create a .env file in your project root.

What's needed:

  • OPENAI_API_KEY: Your OpenAI API key for GPT model access
  • COMPOSIO_API_KEY: Your Composio API key for tool access
  • COMPOSIO_USER_ID: A unique identifier for the user session

Import required modules and validate environment

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Composio } from "@composio/core";
import * as readline from "readline";
import { streamText, type ModelMessage, stepCountIs } from "ai";
import { experimental_createMCPClient as createMCPClient } from "@ai-sdk/mcp";

const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!process.env.OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey,
});
What's happening:
  • We're importing all necessary libraries including Vercel AI SDK's OpenAI provider and Composio
  • The dotenv/config import automatically loads environment variables
  • The MCP client import enables connection to Composio's tool server

Create Tool Router session and initialize MCP client

typescript
async function main() {
  // Create a tool router session for the user
  const { session } = await composio.create(composioUserID!, {
    toolkits: ["twitter"],
  });

  const mcpUrl = session.mcp.url;
What's happening:
  • We're creating a Tool Router session that gives your agent access to Twitter tools
  • The create method takes the user ID and specifies which toolkits should be available
  • The returned mcp object contains the URL and authentication headers needed to connect to the MCP server
  • This session provides access to all Twitter-related tools through the MCP protocol

Connect to MCP server and retrieve tools

typescript
const mcpClient = await createMCPClient({
  transport: {
    type: "http",
    url: mcpUrl,
    headers: session.mcp.headers, // Authentication headers for the Composio MCP server
  },
});

const tools = await mcpClient.tools();
What's happening:
  • We're creating an MCP client that connects to our Composio Tool Router session via HTTP
  • The mcp.url provides the endpoint, and mcp.headers contains authentication credentials
  • The type: "http" is important - Composio requires HTTP transport
  • tools() retrieves all available Twitter tools that the agent can use

Initialize conversation and CLI interface

typescript
let messages: ModelMessage[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
console.log(
  "Ask any questions related to twitter, like summarize my last 5 emails, send an email, etc... :)))\n",
);

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: "> ",
});

rl.prompt();
What's happening:
  • We initialize an empty messages array to maintain conversation history
  • A readline interface is created to accept user input from the command line
  • Instructions are displayed to guide the user on how to interact with the agent

Handle user input and stream responses with real-time tool feedback

typescript
rl.on("line", async (userInput: string) => {
  const trimmedInput = userInput.trim();

  if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
    console.log("\nGoodbye!");
    rl.close();
    process.exit(0);
  }

  if (!trimmedInput) {
    rl.prompt();
    return;
  }

  messages.push({ role: "user", content: trimmedInput });
  console.log("\nAgent is thinking...\n");

  try {
    const stream = streamText({
      model: openai("gpt-5"),
      messages,
      tools,
      toolChoice: "auto",
      stopWhen: stepCountIs(10),
      onStepFinish: (step) => {
        for (const toolCall of step.toolCalls) {
          console.log(`[Using tool: ${toolCall.toolName}]`);
          }
          if (step.toolCalls.length > 0) {
            console.log(""); // Add space after tool calls
          }
        },
      });

      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk);
      }

      console.log("\n\n---\n");

      // Get final result for message history
      const response = await stream.response;
      if (response?.messages?.length) {
        messages.push(...response.messages);
      }
    } catch (error) {
      console.error("\nAn error occurred while talking to the agent:");
      console.error(error);
      console.log(
        "\nYou can try again or restart the app if it keeps happening.\n",
      );
    } finally {
      rl.prompt();
    }
  });

  rl.on("close", async () => {
    await mcpClient.close();
    console.log("\n👋 Session ended.");
    process.exit(0);
  });
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
What's happening:
  • We use streamText instead of generateText to stream responses in real-time
  • toolChoice: "auto" allows the model to decide when to use Twitter tools
  • stopWhen: stepCountIs(10) allows up to 10 steps for complex multi-tool operations
  • onStepFinish callback displays which tools are being used in real-time
  • We iterate through the text stream to create a typewriter effect as the agent responds
  • The complete response is added to conversation history to maintain context
  • Errors are caught and displayed with helpful retry suggestions

Complete Code

Here's the complete code to get you started with Twitter and Vercel AI SDK:

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Composio } from "@composio/core";
import * as readline from "readline";
import { streamText, type ModelMessage, stepCountIs } from "ai";
import { experimental_createMCPClient as createMCPClient } from "@ai-sdk/mcp";

const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!process.env.OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey,
});

async function main() {
  // Create a tool router session for the user
  const { session } = await composio.create(composioUserID!, {
    toolkits: ["twitter"],
  });

  const mcpUrl = session.mcp.url;

  const mcpClient = await createMCPClient({
    transport: {
      type: "http",
      url: mcpUrl,
      headers: session.mcp.headers, // Authentication headers for the Composio MCP server
    },
  });

  const tools = await mcpClient.tools();

  let messages: ModelMessage[] = [];

  console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
  console.log(
    "Ask any questions related to twitter, like summarize my last 5 emails, send an email, etc... :)))\n",
  );

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: "> ",
  });

  rl.prompt();

  rl.on("line", async (userInput: string) => {
    const trimmedInput = userInput.trim();

    if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
      console.log("\nGoodbye!");
      rl.close();
      process.exit(0);
    }

    if (!trimmedInput) {
      rl.prompt();
      return;
    }

    messages.push({ role: "user", content: trimmedInput });
    console.log("\nAgent is thinking...\n");

    try {
      const stream = streamText({
        model: openai("gpt-5"),
        messages,
        tools,
        toolChoice: "auto",
        stopWhen: stepCountIs(10),
        onStepFinish: (step) => {
          for (const toolCall of step.toolCalls) {
            console.log(`[Using tool: ${toolCall.toolName}]`);
          }
          if (step.toolCalls.length > 0) {
            console.log(""); // Add space after tool calls
          }
        },
      });

      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk);
      }

      console.log("\n\n---\n");

      // Get final result for message history
      const response = await stream.response;
      if (response?.messages?.length) {
        messages.push(...response.messages);
      }
    } catch (error) {
      console.error("\nAn error occurred while talking to the agent:");
      console.error(error);
      console.log(
        "\nYou can try again or restart the app if it keeps happening.\n",
      );
    } finally {
      rl.prompt();
    }
  });

  rl.on("close", async () => {
    await mcpClient.close();
    console.log("\n👋 Session ended.");
    process.exit(0);
  });
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});

Conclusion

You've successfully built a Twitter agent using the Vercel AI SDK with streaming capabilities! This implementation provides a powerful foundation for building AI applications with natural language interfaces and real-time feedback.

Key features of this implementation:

  • Real-time streaming responses for a better user experience with typewriter effect
  • Live tool execution feedback showing which tools are being used as the agent works
  • Dynamic tool loading through Composio's Tool Router with secure authentication
  • Multi-step tool execution with configurable step limits (up to 10 steps)
  • Comprehensive error handling for robust agent execution
  • Conversation history maintenance for context-aware responses

You can extend this further by adding custom error handling, implementing specific business logic, or integrating additional Composio toolkits to create multi-app workflows.

How to build Twitter MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and Twitter MCP?

With a standalone Twitter MCP server, the agents and LLMs can only access a fixed set of Twitter tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Twitter and many other apps based on the task at hand, all through a single MCP endpoint.

Can I use Tool Router MCP with Vercel AI SDK?

Yes, you can. Vercel AI SDK fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Twitter tools.

Can I manage the permissions and scopes for Twitter while using Tool Router?

Yes, absolutely. You can configure which Twitter scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

How safe is my data with Composio Tool Router?

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Twitter data and credentials are handled as safely as possible.

Used by agents from

Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai

Never worry about agent reliability

We handle tool reliability, observability, and security so you never have to second-guess an agent action.