How to integrate Slack MCP with Vercel AI SDK v6

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Slack logo
Vercel AI SDK logo
divider

Introduction

This guide walks you through connecting Slack to Vercel AI SDK v6 using the Composio tool router. By the end, you'll have a working Slack agent that can send reminder to marketing channel at 10am, add reaction to latest team message, archive inactive project channel after review through natural language commands.

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

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

Also integrate Slack with

TL;DR

Here's what you'll learn:
  • How to set up and configure a Vercel AI SDK agent with Slack integration
  • Using Composio's Tool Router to dynamically load and access Slack 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 Slack MCP server, and what's possible with it?

The Slack MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Slack account. It provides structured and secure access to your messages, channels, files, and reminders, so your agent can send messages, manage conversations, organize reminders, and interact with channel content—all on your behalf.

  • Automated messaging and reminders: Let your agent send messages to channels, create reminders with natural language timing, and help your team stay on track.
  • Emoji and reaction management: Have the agent add custom emoji, create emoji aliases, or react to messages with specific emojis to keep conversations lively and expressive.
  • Channel and conversation organization: Ask the agent to archive inactive channels or close direct message threads, keeping your Slack workspace neat and focused.
  • File and external content sharing: Enable your agent to add references to external files from services like Google Drive or Dropbox, making collaboration seamless without leaving Slack.
  • Starring and prioritizing items: Let the agent star important channels, files, or messages so your priorities are always front and center.

Supported Tools & Triggers

Tools
Triggers
Add call participantsRegisters new participants added to a Slack call.
Add emojiAdds a custom emoji to a Slack workspace given a unique name and an image URL; subject to workspace emoji limits.
Add an emoji aliasAdds an alias for an existing custom emoji in a Slack Enterprise Grid organization.
Add Enterprise user to workspaceAdds an Enterprise user to a workspace.
Add reaction to messageAdds a specified emoji reaction to an existing message in a Slack channel, identified by its timestamp; does not remove or retrieve reactions.
Add a remote fileAdds a reference to an external file (e.
Add a star to an itemStars a channel, file, file comment, or a specific message in Slack.
Search for channels in Enterprise organizationTool to search for public or private channels in an Enterprise organization.
Test Slack API connectionTool to check API calling code by testing connectivity and authentication to the Slack API.
Archive a Slack conversationArchives a Slack conversation by its ID, rendering it read-only and hidden while retaining history, ideal for cleaning up inactive channels; be aware that some channels (like #general or certain DMs) cannot be archived and this may impact connected integrations.
Real-time searchSearch Slack messages, files, channels, and users via Real-time Search API.
Check search capabilitiesCheck if semantic (AI-powered) search is available on the Slack workspace.
Close conversation channelCloses a Slack direct message (DM) or multi-person direct message (MPDM) channel, removing it from the user's sidebar without deleting history; this action affects only the calling user's view.
Convert public channel to privateConvert a public Slack channel to private using the Admin API.
Create a reminderCreates a Slack reminder with specified text and time; time accepts Unix timestamps, seconds from now, or natural language (e.
Create Slack CanvasCreates a new Slack Canvas with the specified title and optional content.
Create channelInitiates a public or private channel-based conversation in a Slack workspace.
Create a channel-based conversationCreates a new public or private Slack channel with a unique name; the channel can be org-wide, or team-specific if `team_id` is given (required if `org_wide` is false or not provided).
Create Enterprise teamTool to create an Enterprise team in Slack.
Create a Slack user groupCreates a new User Group (often referred to as a subteam) in a Slack workspace.
Customize URL unfurlCustomizes URL previews (unfurling) in a specific Slack message using a URL-encoded JSON in `unfurls` to define custom content or remove existing previews.
Delete Slack CanvasDeletes a Slack Canvas permanently and irreversibly.
Delete a public or private channelPermanently and irreversibly deletes a specified public or private channel, including all its messages and files, within a Slack Enterprise Grid organization.
Delete a file by IDPermanently deletes an existing file from a Slack workspace using its unique file ID; this action is irreversible and also removes any associated comments or shares.
Delete file commentDeletes a specific comment from a file in Slack; this action is irreversible.
Delete a Slack reminderDeletes an existing Slack reminder, typically when it is no longer relevant or a task is completed; this operation is irreversible.
Delete a message from a chatDeletes a message, identified by its channel ID and timestamp, from a Slack channel, private group, or direct message conversation; the authenticated user or bot must be the original poster.
Delete scheduled chat messageDeletes a pending, unsent scheduled message from the specified Slack channel, identified by its `scheduled_message_id`.
Delete user profile photoDeletes the Slack profile photo for the user identified by the token, reverting them to the default avatar; this action is irreversible and succeeds even if no custom photo was set.
Disable a Slack user groupDisables a specified, currently enabled Slack User Group by its unique ID, effectively archiving it by setting its 'date_delete' timestamp; the group is not permanently deleted and can be re-enabled.
Download Slack fileTool to download Slack file content and convert it to a publicly accessible URL.
Edit Slack CanvasEdits a Slack Canvas with granular control over content placement.
Share file public urlEnables public sharing for an existing Slack file by generating a publicly accessible URL; this action does not create new files.
Enable a user groupEnables a disabled User Group in Slack using its ID, reactivating it for mentions and permissions; this action only changes the enabled status and cannot create new groups or modify other properties.
End a callEnds an ongoing Slack call, identified by its ID (obtained from `calls.
End DND sessionEnds the authenticated user's current Do Not Disturb (DND) session in Slack, affecting only DND status and making them available; if DND is not active, Slack acknowledges the request without changing status.
End snoozeEnds the current user's snooze mode immediately.
Fetch conversation historyFetches a chronological list of messages and events from a specified Slack conversation, accessible by the authenticated user/bot, with options for pagination and time range filtering.
Fetch item reactionsFetches reactions for a Slack message, file, or file comment.
Retrieve conversation repliesRetrieves replies to a specific parent message in a Slack conversation, using the channel ID and the parent message's timestamp (`ts`).
Fetch team infoFetches comprehensive metadata about the current Slack team, or a specified team if the provided ID is accessible.
Find channelsFind channels in a Slack workspace by any criteria - name, topic, purpose, or description.
Lookup users by emailRetrieves the Slack user object for an active user by their registered email address; requires the users:read.
Find usersFind users in a Slack workspace by any criteria - email, name, display name, or other text.
Get Audit Action TypesTool to retrieve information about action types available in the Slack Audit Logs API.
Get Audit SchemasTool to retrieve object schema information from the Slack Audit Logs API.
Fetch bot user informationFetches information for a specified, existing Slack bot user; will not work for regular user accounts or other integration types.
Retrieve call informationRetrieves a point-in-time snapshot of a specific Slack call's information.
Get channel conversation preferencesRetrieves conversation preferences (e.
Get reminder informationRetrieves detailed information for an existing Slack reminder specified by its ID; this is a read-only operation.
Get remote fileRetrieve information about a remote file added to Slack via the files.
Retrieve team profile detailsRetrieves all profile field definitions for a Slack team, optionally filtered by visibility, to understand the team's profile structure.
Get team DND statusRetrieves a user's current Do Not Disturb status.
Retrieve user presenceRetrieves a Slack user's current real-time presence (e.
Get workspace connections for channelTool to get all workspaces a channel is connected to within an Enterprise org.
Fetch workspace settings informationRetrieves detailed settings for a specific Slack workspace, primarily for administrators in an Enterprise Grid organization to view or audit workspace configurations.
Invite users to a Slack channelInvites users to an existing Slack channel using their valid Slack User IDs.
Invite users to channelInvites users to a specified Slack channel; this action is restricted to Enterprise Grid workspaces and requires the authenticated user to be a member of the target channel.
Invite user to workspaceInvites a user to a Slack workspace and specified channels by email; use `resend=True` to re-process an existing invitation for a user not yet signed up.
Join conversation by channel idJoins an existing Slack conversation (public channel, private channel, or multi-person direct message) by its ID, if the authenticated user has permission.
Leave conversation channelLeaves a Slack conversation given its channel ID; fails if leaving as the last member of a private channel or if used on a Slack Connect channel.
List approved appsTool to list approved apps for an Enterprise Grid organization or workspace.
List app requestsTool to list pending app installation requests for a team/workspace.
List admin emojiList custom emoji across an Enterprise Grid organization.
List all channelsLists conversations available to the user with various filters and search options.
List all usersRetrieves a paginated list of all users with profile details, status, and team memberships in a Slack workspace; data may not be real-time.
List approved workspace invite requestsList all approved workspace invite requests with pagination support.
List authorized teamsObtains a paginated list of workspaces your org-wide app has been approved for.
List conversationsList conversations (channels/DMs) accessible to a specified user (or the authenticated user if no user ID is provided), respecting shared membership for non-public channels.
List team custom emojisRetrieves all custom emojis for the Slack workspace (image URLs or aliases), not standard Unicode emojis; does not include usage statistics or creation dates.
List denied workspace invite requestsTool to list all denied workspace invite requests with details about who denied them and when.
List Enterprise teamsList all teams (workspaces) in a Slack Enterprise Grid organization with pagination support.
List Slack filesLists files and their metadata within a Slack workspace, filterable by user, channel, timestamp, or type; returns metadata only, not file content.
List IDP groups linked to channelLists IDP groups that have restricted access to a private Slack channel.
List pending workspace invite requestsTool to list all pending workspace invite requests.
List pinned items in a channelRetrieves all messages and files pinned to a specified channel; the caller must have access to this channel.
List remindersLists all reminders with their details for the authenticated Slack user; returns an empty array if no reminders exist (valid state, not an error).
List remote filesRetrieve information about a team's remote files.
List Restricted AppsTool to list restricted apps for an org or workspace.
List scheduled messagesRetrieves a list of pending (not yet delivered) messages scheduled in a specific Slack channel, or across all accessible channels if no channel ID is provided, optionally filtered by time and paginated.
List starred itemsLists items starred by a user.
List all users in a user groupRetrieves a list of all user IDs within a specified Slack user group, with an option to include users from disabled groups.
List user groupsLists user groups in a Slack workspace, including user-created and default groups; results for large workspaces may be paginated.
List user reactionsLists all reactions added by a specific user to messages, files, or file comments in Slack, useful for engagement analysis when the item content itself is not required.
List workspace adminsTool to list all admins on a given Slack workspace.
List workspace ownersTool to list all owners on a given Slack workspace.
List admin usersRetrieves a paginated list of admin users for a specified Slack workspace.
Lookup Canvas SectionsLooks up section IDs in a Slack Canvas for use with targeted edit operations.
Open DMOpens or resumes a Slack direct message (DM) or multi-person direct message (MPIM) by providing either user IDs or an existing channel ID.
Pin an item to a channelPins a message to a specified Slack channel; the message must not already be pinned.
Read Audit LogsRead Slack Enterprise Grid Audit Logs (logins, admin changes, app installs, channel/privacy changes, etc.
Remove call participantsRegisters participants removed from a Slack call.
Remove emojiTool to remove a custom emoji across an Enterprise Grid organization.
Remove reaction from itemRemoves an emoji reaction from a message, file, or file comment in Slack.
Remove remote fileRemoves the Slack reference to an external file (which must have been previously added via the remote files API), specified by either its `external_id` or `file` ID (one of which is required), without deleting the actual external file.
Remove a star from an itemRemoves a star from a previously starred Slack item (message, file, file comment, channel, group, or DM), requiring identification via `file`, `file_comment`, `channel` (for channel/group/DM), or both `channel` and `timestamp` (for a message).
Remove user from conversationRemoves a specified user from a Slack conversation (channel); the caller must have permissions to remove users and cannot remove themselves using this action.
Remove user from workspaceTool to remove a user from a Slack workspace.
Rename a conversationRenames a Slack channel, automatically adjusting the new name to meet naming conventions (e.
Rename an emojiRenames an existing custom emoji in a Slack workspace, updating all its instances.
Reset user sessionsTool to wipe all valid sessions on all devices for a given user.
Restrict app installationRestrict an app for installation on a workspace.
Retrieve a user's identity detailsRetrieves the authenticated user's and their team's identity, with details varying based on OAuth scopes (e.
Retrieve conversation informationRetrieves metadata for a Slack conversation by ID (e.
Get conversation membersRetrieves a paginated list of active member IDs (not names, emails, or presence) for a specified Slack public channel, private channel, DM, or MPIM.
Retrieve user DND statusRetrieves a Slack user's current Do Not Disturb (DND) status to determine their availability before interaction; any specified user ID must be a valid Slack user ID.
Retrieve detailed file informationRetrieves detailed metadata and paginated comments for a specific Slack file ID; does not download file content.
Retrieve detailed user informationRetrieves comprehensive information for a valid Slack user ID, excluding message history and channel memberships.
Retrieve message permalinkRetrieves a permalink URL for a specific message in a Slack channel or conversation; the permalink respects Slack's privacy settings.
Retrieve user profile informationRetrieves profile information for a specified Slack user (defaults to the authenticated user if `user` ID is omitted); a provided `user` ID must be valid.
Revoke a file's public urlRevokes a Slack file's public URL, making it private; this is a no-op if not already public and is irreversible.
Start RTM sessionStarts a Real Time Messaging session and returns a WebSocket URL.
Schedule messageSchedules a message to a Slack channel, DM, or private group for a future time (`post_at`), requiring `text`, `blocks`, or `attachments` for content; scheduling is limited to 120 days in advance.
Get SCIM service provider configurationTool to retrieve SCIM service provider configuration from Slack.
Search all contentTool to search all messages and files.
Search messagesWorkspace‑wide Slack message search with date ranges and filters.
Send ephemeral messageSends an ephemeral message visible only to the specified `user` in a channel; other channel members cannot see it.
Share a me message in a channelSends a 'me message' (e.
Send messagePosts a message to a Slack channel, DM, or private group; requires at least one content field (`markdown_text`, `text`, `blocks`, or `attachments`) — omitting all causes a `no_text` error.
Set admin userPromotes an existing workspace member (guest, regular user, or owner) to admin status.
Set conversation preferencesSets the posting permissions for a public or private channel in Slack.
Set a conversation's purposeSets the purpose (a short description of its topic/goal, displayed in the header) for a Slack conversation; the calling user must be a member.
Set default channelsTool to set the default channels of a workspace.
Set DND durationTurns on Do Not Disturb mode for the current user, or changes its duration.
Set profile photoThis method allows the user to set their profile image.
Set conversation read cursorMarks a message, specified by its timestamp (`ts`), as the most recently read for the authenticated user in the given `channel`, provided the user is a member of the channel and the message exists within it.
Set conversation topicSets or updates the topic for a specified Slack conversation.
Set user presenceManually sets a user's Slack presence, overriding automatic detection; this setting persists across connections but can be overridden by user actions or Slack's auto-away (e.
Set Slack user profile informationUpdates a Slack user's profile, setting either individual fields or multiple fields via a JSON object.
Set workspace descriptionSet the description of a given workspace.
Set workspace iconSets the icon of a workspace.
Set workspace nameSet the name of a given Slack workspace.
Set workspace ownerSet an existing guest, regular user, or admin user to be a workspace owner.
Set workspaces for channelSet the workspaces in an Enterprise grid org that connect to a channel.
Share a remote file in channelsShares a remote file, which must already be registered with Slack, into specified Slack channels or direct message conversations.
Start callRegisters a new call in Slack using `calls.
Test authenticationChecks authentication and tells you who you are.
Unarchive channelReverses conversation archival.
Unpin message from channelUnpins a message, identified by its timestamp, from a specified channel if the message is currently pinned there; this operation is destructive.
Update call informationUpdates the title, join URL, or desktop app join URL for an existing Slack call identified by its ID.
Update an existing remote fileUpdates metadata or content details for an existing remote file in Slack; this action cannot upload new files or change the fundamental file type.
Update a Slack messageUpdates a Slack message, identified by `channel` ID and `ts` timestamp, by modifying its `text`, `attachments`, or `blocks`; provide at least one content field, noting `attachments`/`blocks` are replaced if included (`[]` clears them).
Update Slack user groupUpdates an existing Slack User Group, which must be specified by an existing `usergroup` ID, with new optional details such as its name, description, handle, or default channels.
Update user group membersReplaces all members of an existing Slack User Group with a new list of valid user IDs.
Upload or create a file in SlackUpload files, images, screenshots, documents, or any media to Slack channels or threads.

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

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 { 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: ["slack"],
  });

  const mcpUrl = session.mcp.url;
What's happening:
  • We're creating a Tool Router session that gives your agent access to Slack 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 Slack-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 Slack 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 slack, 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 Slack 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 Slack 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: ["slack"],
  });

  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 slack, 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 Slack 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 Slack MCP Agent with another framework

FAQ

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

With a standalone Slack MCP server, the agents and LLMs can only access a fixed set of Slack tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Slack 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 v6?

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 Slack tools.

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

Yes, absolutely. You can configure which Slack 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 Slack data and credentials are handled as safely as possible.

Used by agents from

Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
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.