How to integrate Slack MCP with Mastra AI

Framework Integration Gradient
Slack Logo
Mastra AI Logo
divider

Introduction

This guide walks you through connecting Slack to Mastra AI 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, star important message from project manager through natural language commands.

This guide will help you understand how to give your Mastra AI 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.

TL;DR

Here's what you'll learn:
  • Set up your environment so Mastra, OpenAI, and Composio work together
  • Create a Tool Router session in Composio that exposes Slack tools
  • Connect Mastra's MCP client to the Composio generated MCP URL
  • Fetch Slack tool definitions and attach them as a toolset
  • Build a Mastra agent that can reason, call tools, and return structured results
  • Run an interactive CLI where you can chat with your Slack agent

What is Mastra AI?

Mastra AI is a TypeScript framework for building AI agents with tool support. It provides a clean API for creating agents that can use external services through MCP.

Key features include:

  • MCP Client: Built-in support for Model Context Protocol servers
  • Toolsets: Organize tools into logical groups
  • Step Callbacks: Monitor and debug agent execution
  • OpenAI Integration: Works with OpenAI models via @ai-sdk/openai

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 an emoji aliasAdds an alias for an existing custom emoji in a slack enterprise grid organization.
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.
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 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.
Archive a public or private channelArchives a slack public or private channel, making it read-only; the primary 'general' channel cannot be archived.
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.
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.
Create a reminderCreates a slack reminder with specified text and time; time accepts unix timestamps, seconds from now, or natural language (e.
Create a Slack user groupCreates a new user group (often referred to as a subteam) in a slack workspace.
Create channelInitiates a public or private channel-based conversation
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).
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 file commentDeletes a specific comment from a file in slack; this action is irreversible.
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 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 scheduled chat messageDeletes a pending, unsent scheduled message from the specified slack channel, identified by its `scheduled message id`.
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 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.
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.
Share file public urlEnables public sharing for an existing slack file by generating a publicly accessible url; this action does not create new files.
End a callEnds an ongoing slack call, identified by its id (obtained from `calls.
End snoozeEnds the current user's snooze mode immediately.
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.
Fetch bot user informationFetches information for a specified, existing slack bot user; will not work for regular user accounts or other integration types.
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, requiring one of: channel and timestamp; file id; or file comment id.
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.
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.
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; fails with 'users not found' if the email is unregistered or the user is inactive.
Find usersFind users in a slack workspace by any criteria - email, name, display name, or other text.
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.
Get team DND statusRetrieves a user's current do not disturb status.
Retrieve user presenceRetrieves a slack user's current real-time presence (e.
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 all channelsLists conversations available to the user with various filters and search options.
List all usersRetrieves a paginated list of all users, including comprehensive details, profile information, status, and team memberships, in a slack workspace; data may not be real-time.
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 conversationsRetrieves conversations accessible to a specified user (or the authenticated user if no user id is provided), respecting shared membership for non-public channels.
List Slack filesLists files and their metadata within a slack workspace, filterable by user, channel, timestamp, or type; this action returns metadata only, not file content.
List remindersLists all reminders with their details for the authenticated slack user; returns an empty list if no reminders exist.
List remote filesRetrieve information about a team's remote files.
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 pinned items in a channelRetrieves all messages and files pinned to a specified channel; the caller must have access to this channel.
List starred itemsLists items starred by a user.
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 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 admin usersRetrieves a paginated list of admin users for a specified slack workspace.
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.
Mark reminder as completeMarks a specific slack reminder as complete using its `reminder` id; **deprecated**: this slack api endpoint ('reminders.
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.
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 call participantsRegisters participants removed from a slack call.
Remove reaction from itemRemoves an emoji reaction from a message, file, or file comment in slack.
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.
Rename a Slack channelRenames a public or private slack channel; for enterprise grid workspaces, the user must be a workspace admin or channel manager.
Retrieve a user's identity detailsRetrieves the authenticated user's and their team's identity, with details varying based on oauth scopes (e.
Retrieve call informationRetrieves a point-in-time snapshot of a specific slack call's information.
Retrieve conversation informationRetrieves metadata for a slack conversation by id (e.
Get conversation membersRetrieves a paginated list of active member ids for a specified slack public channel, private channel, direct message (dm), or multi-person direct message (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 team profile detailsRetrieves all profile field definitions for a slack team, optionally filtered by visibility, to understand the team's profile structure.
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.
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.
Search messagesWorkspace‑wide slack message search with date ranges and filters.
Send ephemeral messageSends an ephemeral message to a user in a channel.
Send messagePosts a message to a slack channel, direct message, or private group; requires content via `text`, `blocks`, or `attachments`.
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 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 Slack user profile informationUpdates a slack user's profile, setting either individual fields or multiple fields via a json object.
Set conversation topicSets or updates the topic for a specified slack conversation.
Share a me message in a channelSends a 'me message' (e.
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.
Start real time messaging sessionInitiates a slack rtm session providing a single-use websocket url (valid 30s) for event streaming; does not set initial presence status.
Unarchive a public or private channelUnarchives a specified public or private slack channel that is currently archived, using its channel id.
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 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 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 call informationUpdates the title, join url, or desktop app join url for an existing slack call identified by its id.
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 SlackUploads a file to slack, requiring either `content` (for text) or `file` (for binary data), optionally sharing it in specified `channels` or as a reply via `thread ts`.

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 starting, make sure you have:
  • Node.js 18 or higher
  • A Composio account with an active API key
  • An OpenAI API key
  • Basic familiarity with TypeScript

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key.
  • You need credits or a connected billing setup to use the models.
  • Store the key somewhere safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Go to Settings and copy your API key.
  • This key lets your Mastra agent talk to Composio and reach Slack through MCP.

Install dependencies

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

Install the required packages.

What's happening:

  • @composio/core is the Composio SDK for creating MCP sessions
  • @mastra/core provides the Agent class
  • @mastra/mcp is Mastra's MCP client
  • @ai-sdk/openai is the model wrapper for OpenAI
  • dotenv loads environment variables from .env

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key_here

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your requests to Composio
  • COMPOSIO_USER_ID tells Composio which user this session belongs to
  • OPENAI_API_KEY lets the Mastra agent call OpenAI models

Import libraries and validate environment

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

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

if (!openaiAPIKey) 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 as string,
});
What's happening:
  • dotenv/config auto loads your .env so process.env.* is available
  • openai gives you a Mastra compatible model wrapper
  • Agent is the Mastra agent that will call tools and produce answers
  • MCPClient connects Mastra to your Composio MCP server
  • Composio is used to create a Tool Router session

Create a Tool Router session for Slack

typescript
async function main() {
  const session = await composio.create(
    composioUserID as string,
    {
      toolkits: ["slack"],
    },
  );

  const composioMCPUrl = session.mcp.url;
  console.log("Slack MCP URL:", composioMCPUrl);
What's happening:
  • create spins up a short-lived MCP HTTP endpoint for this user
  • The toolkits array contains "slack" for Slack access
  • session.mcp.url is the MCP URL that Mastra's MCPClient will connect to

Configure Mastra MCP client and fetch tools

typescript
const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      nasdaq: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

console.log("Fetching MCP tools from Composio...");
const composioTools = await mcpClient.getTools();
console.log("Number of tools:", Object.keys(composioTools).length);
What's happening:
  • MCPClient takes an id for this client and a list of MCP servers
  • The headers property includes the x-api-key for authentication
  • getTools fetches the tool definitions exposed by the Slack toolkit

Create the Mastra agent

typescript
const agent = new Agent({
    name: "slack-mastra-agent",
    instructions: "You are an AI agent with Slack tools via Composio.",
    model: "openai/gpt-5",
  });
What's happening:
  • Agent is the core Mastra agent
  • name is just an identifier for logging and debugging
  • instructions guide the agent to use tools instead of only answering in natural language
  • model uses openai("gpt-5") to configure the underlying LLM

Set up interactive chat interface

typescript
let messages: AiMessageType[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end.\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({
    id: crypto.randomUUID(),
    role: "user",
    content: trimmedInput,
  });

  console.log("\nAgent is thinking...\n");

  try {
    const response = await agent.generate(messages, {
      toolsets: {
        slack: composioTools,
      },
      maxSteps: 8,
    });

    const { text } = response;

    if (text && text.trim().length > 0) {
      console.log(`Agent: ${text}\n`);
        messages.push({
          id: crypto.randomUUID(),
          role: "assistant",
          content: text,
        });
      }
    } catch (error) {
      console.error("\nError:", error);
    }

    rl.prompt();
  });

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

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
What's happening:
  • messages keeps the full conversation history in Mastra's expected format
  • agent.generate runs the agent with conversation history and Slack toolsets
  • maxSteps limits how many tool calls the agent can take in a single run
  • onStepFinish is a hook that prints intermediate steps for debugging

Complete Code

Here's the complete code to get you started with Slack and Mastra AI:

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

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

if (!openaiAPIKey) 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 as string });

async function main() {
  const session = await composio.create(composioUserID as string, {
    toolkits: ["slack"],
  });

  const composioMCPUrl = session.mcp.url;

  const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      slack: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

  const composioTools = await mcpClient.getTools();

  const agent = new Agent({
    name: "slack-mastra-agent",
    instructions: "You are an AI agent with Slack tools via Composio.",
    model: "openai/gpt-5",
  });

  let messages: AiMessageType[] = [];

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

  rl.prompt();

  rl.on("line", async (input: string) => {
    const trimmed = input.trim();
    if (["exit", "quit"].includes(trimmed.toLowerCase())) {
      rl.close();
      return;
    }

    messages.push({ id: crypto.randomUUID(), role: "user", content: trimmed });

    const { text } = await agent.generate(messages, {
      toolsets: { slack: composioTools },
      maxSteps: 8,
    });

    if (text) {
      console.log(`Agent: ${text}\n`);
      messages.push({ id: crypto.randomUUID(), role: "assistant", content: text });
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main();

Conclusion

You've built a Mastra AI agent that can interact with Slack through Composio's Tool Router. You can extend this further by:
  • Adding other toolkits like Gmail, Slack, or GitHub
  • Building a web-based chat interface around this agent
  • Using multiple MCP endpoints to enable cross-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 Mastra AI?

Yes, you can. Mastra AI 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.