How to integrate Twitter MCP with Vercel AI SDK v6

This guide walks you through connecting Twitter to Vercel AI SDK v6 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 your conference list, retrieve your most recent bookmarked tweets 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.

Twitter logoTwitter
Oauth2

Twitter is a social media platform for sharing real-time updates, conversations, and news. Stay connected, informed, and engaged with communities worldwide.

78 Tools

Introduction

This guide walks you through connecting Twitter to Vercel AI SDK v6 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 your conference list, retrieve your most recent bookmarked tweets 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.

Also integrate Twitter with

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 via @ai-sdk/mcp
  • Step Counting: Control multi-step tool execution with stopWhen: stepCountIs()
  • 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.

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

What is Composio SDK?

Composio's Composio SDK 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 Composio SDK

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

How the Composio SDK works

The Composio SDK 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

Step by step09 STEPS
1

Prerequisites

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

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.
3

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
4

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
5

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 { 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
6

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
7

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
8

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
9

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 { 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.
TOOLS

Supported Tools

Every Twitter action and event your agent gets out of the box.

Add a list member

Adds a user to a specified Twitter List; the list must be owned by the authenticated user.

Add post to bookmarks

Adds a specified, existing, and accessible Tweet to a user's bookmarks, with success indicated by the 'bookmarked' field in the response.

Append Media Upload

Append data chunk to an ongoing media upload session on X/Twitter.

Get bookmarks by user

Retrieves Tweets bookmarked by the authenticated user, where the provided User ID must match the authenticated user's ID.

Create activity subscription

Tool to create a subscription for an X activity event.

Create compliance job

Creates 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 group DM conversation

Creates a new group Direct Message (DM) conversation on Twitter.

Create a list

Creates 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 post

Creates a Tweet on Twitter; `text` is required unless `card_uri`, `media_media_ids`, `poll_options`, or `quote_tweet_id` is provided.

Delete direct message

Permanently 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 list

Permanently 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.

Get followers by user id

Retrieves a list of users who follow a specified public Twitter user ID.

Get following by user ID

Retrieves users followed by a specific Twitter user, allowing pagination and customization of returned user and tweet data fields via expansions.

Follow a list

Allows 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.

Follow a user

Allows 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 tweets

Searches the full archive of public Tweets from March 2006 onwards; use 'start_time' and 'end_time' together for a defined time window.

Get users blocked by user ID

Retrieves the authenticated user's own block list.

Retrieve compliance job by id

Retrieves status, download/upload URLs, and other details for an existing Twitter compliance job specified by its unique ID.

Retrieve compliance jobs

Returns a list of recent compliance jobs, filtered by type (tweets or users) and optionally by status.

Get DM events for a DM conversation

Fetches 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 DM events by ID

Fetches 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.

Lookup list by ID

Returns 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.

Get list followers

Fetches 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.

Fetch list members by id

Fetches members of a specific Twitter List, identified by its unique ID.

Get Media Upload Status

Get the processing status of uploaded media (videos/GIFs) on X/Twitter.

Get muted users

Returns user objects muted by the X user identified by the `id` path parameter.

Fetch OpenAPI specification

Fetches the OpenAPI specification (JSON) for Twitter's API v2, used to programmatically understand the API's structure for developing client libraries or tools.

Get Post analytics

Tool to retrieve analytics data for specified Posts within a defined time range.

Get post retweeters

Retrieves users who publicly retweeted a specified public Post ID, excluding Quote Tweets and retweets from private accounts.

Retrieve retweets of a post

Retrieves Tweets that Retweeted a specified public or authenticated-user-accessible Tweet ID, optionally customizing the response with fields and expansions.

Fetch tweet usage data

Fetches Tweet usage statistics for a Project (e.

Get recent direct message events

Returns recent Direct Message events for the authenticated user, such as new messages or changes in conversation participants.

Look up space by ID

Retrieves details for a Twitter Space by its ID, allowing for customization and expansion of related data, provided the Space ID is valid and accessible.

Retrieve posts from a space

Retrieves Tweets that were shared/posted during a Twitter Space broadcast.

Get spaces by creator IDs

Retrieves Twitter Spaces created by a list of specified User IDs, with options to customize returned data fields.

Get space information by IDs

Fetches detailed information for one or more Twitter Spaces (live, scheduled, or ended) by their unique IDs; at least one Space ID must be provided.

Fetch space ticket buyers list

Retrieves a list of users who purchased tickets for a specific, valid, and ticketed Twitter Space.

Look up user by ID

Retrieves detailed public information for a Twitter user by their ID, optionally expanding related data (e.

Get user's followed lists

Returns metadata (not Tweets) for lists a specific Twitter user follows, optionally including expanded owner details.

Get a user's list memberships

Retrieves 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 lists

Call 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 lists

Retrieves the Lists a specific, existing Twitter user has pinned to their profile to highlight them.

Look up users by IDs

Retrieves detailed information for specified X (formerly Twitter) user IDs, optionally customizing returned fields and expanding related entities.

Set reply visibility

Hides or unhides an existing reply Tweet.

Initialize Media Upload

Initialize a media upload session for X/Twitter.

List post likers

Retrieves users who have liked the Post (Tweet) identified by the provided ID.

List posts timeline by list ID

Fetches the most recent Tweets posted by members of a specified Twitter List.

Mute user by ID

Mutes 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 list

Pins 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 tweet

Irreversibly deletes a specific Tweet by its ID; the Tweet may persist in third-party caches after deletion.

Look up post by id

Fetches comprehensive details for a single Tweet by its unique ID, provided the Tweet exists and is accessible.

Get tweets by IDs

Retrieves detailed information for one or more Posts (Tweets) identified by their unique IDs, allowing selection of specific fields and expansions.

Search recent tweets

Searches 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.

Remove a list member

Removes 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.

Remove a bookmarked post

Removes 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.

Retrieve DM conversation events

Retrieves Direct Message (DM) events for a specific conversation ID on Twitter, useful for analyzing messages and participant activities.

Retrieve posts that quote a post

Retrieves Tweets that quote a specified Tweet, requiring a valid Tweet ID.

Retrieve liked tweets by user ID

Retrieves Tweets liked by a specified Twitter user, provided their liked tweets are public or accessible.

Retweet post

Retweets a Tweet for the authenticated user.

Get full archive search counts

Returns 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`.

Fetch recent tweet counts

Retrieves the count of Tweets matching a specified search query within the last 7 days, aggregated by 'minute', 'hour', or 'day'.

Search for spaces

Searches for Twitter Spaces by a textual query, optionally filtering by state (live, scheduled, all) to discover audio conversations.

Send a new message to a user

Sends 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.

Send a new message to a DM conversation

Sends a message, with optional text and/or media attachments (using pre-uploaded `media_id`s), to a specified Twitter Direct Message conversation.

Get tweets label stream

Stream real-time Tweet label events (apply/remove).

Unfollow a list

Enables 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 user

Allows the authenticated user to unfollow an existing Twitter user (`target_user_id`), which removes the follow relationship.

Unlike post

Allows 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 ID

Unmutes a target user for the authenticated user, allowing them to see Tweets and notifications from the target user again.

Unpin a list

Unpins a List (specified by list_id) from the authenticated user's profile.

Unretweet post

Removes a user's retweet of a specified Post, if the user had previously retweeted it.

Update list attributes

Updates an existing Twitter List's name, description, or privacy status, requiring the List ID and at least one mutable property.

Upload Media

Upload media (images only) to X/Twitter using the v2 API.

Get user reverse chronological timeline

Retrieves the home timeline (reverse chronological feed) for the authenticated Twitter user.

Like a tweet

Allows the authenticated user to like a specific, accessible Tweet, provided neither user has blocked the other and the authenticated user is not restricted from liking.

Look up user by username

Fetches 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 username

Retrieves 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 user

Returns profile information for the currently authenticated X user, customizable via request fields.

FAQ

Frequently asked questions

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.

Yes, you can. Vercel AI SDK v6 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.

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.

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.

Start with Twitter.It takes 30 seconds.

Managed auth, hosted MCP servers, and every Twitter tool your agent needs.Free to start.

Start building