UNPKG

@mastra/core

Version:
335 lines (250 loc) • 13 kB
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt # Slack Add your agent to Slack so people can message it in shared channel threads or direct messages. When someone sends a message, Mastra runs your agent through the normal agent pipeline and streams the response back to Slack. The Slack adapter handles Slack AI indicators and interactive cards for you. ## Installation Install the Slack adapter from the Chat SDK: **npm**: ```bash npm install @chat-adapter/slack ``` **pnpm**: ```bash pnpm add @chat-adapter/slack ``` **Yarn**: ```bash yarn add @chat-adapter/slack ``` **Bun**: ```bash bun add @chat-adapter/slack ``` Add `createSlackAdapter()` to the agent's `channels.adapters` object: ```typescript import { Agent } from '@mastra/core/agent' import { createSlackAdapter } from '@chat-adapter/slack' export const yourAgent = new Agent({ id: 'your-agent', name: 'Your Agent', instructions: 'Help people plan tasks, answer questions, and coordinate work in Slack.', model: 'anthropic/claude-opus-4-7', channels: { adapters: { slack: createSlackAdapter(), }, }, }) ``` ## Create a Slack app To connect your agent, create a Slack app in the workspace where you want it to run. The Slack app controls your agent's display in Slack, its capabilities, and the events it receives. This guide uses a [manifest](https://docs.slack.dev/app-manifests/configuring-apps-with-app-manifests/#creating_manifests): a configuration file that creates the Slack app settings for you. This is the fastest path when you are adding your agent to your own workspace. It doesn't cover the platform OAuth flow where other workspaces install your agent. Create the Slack app from a manifest: 1. Open [api.slack.com/apps](https://api.slack.com/apps). 2. Select **Create an app**. 3. Select **From a manifest**. 4. Choose the workspace where the agent should run. 5. Paste this manifest, then select **Create**. Slack accepts JSON or YAML, so use whichever tab matches the format shown in the app creation modal: **JSON**: ```json { "display_information": { "name": "mastra-agent" }, "features": { "app_home": { "home_tab_enabled": false, "messages_tab_enabled": true, "messages_tab_read_only_enabled": false }, "bot_user": { "display_name": "mastra-agent", "always_online": true } }, "oauth_config": { "scopes": { "bot": [ "im:write", "app_mentions:read", "channels:history", "channels:read", "chat:write", "users:read", "im:read", "im:history" ] }, "pkce_enabled": false }, "settings": { "event_subscriptions": { "request_url": "https://<YOUR-PUBLIC-URL>/api/agents/<YOUR-AGENT-ID>/channels/slack/webhook", "bot_events": ["app_mention", "message.channels", "message.im"] }, "interactivity": { "is_enabled": true, "request_url": "https://<YOUR-PUBLIC-URL>/api/agents/<YOUR-AGENT-ID>/channels/slack/webhook" }, "org_deploy_enabled": false, "socket_mode_enabled": false, "token_rotation_enabled": false, "is_mcp_enabled": false } } ``` **YAML**: ```yaml display_information: name: mastra-agent features: app_home: home_tab_enabled: false messages_tab_enabled: true messages_tab_read_only_enabled: false bot_user: display_name: mastra-agent always_online: true oauth_config: scopes: bot: - im:write - app_mentions:read - channels:history - channels:read - chat:write - users:read - im:read - im:history pkce_enabled: false settings: event_subscriptions: request_url: https://<YOUR-PUBLIC-URL>/api/agents/<YOUR-AGENT-ID>/channels/slack/webhook bot_events: - app_mention - message.channels - message.im interactivity: is_enabled: true request_url: https://<YOUR-PUBLIC-URL>/api/agents/<YOUR-AGENT-ID>/channels/slack/webhook org_deploy_enabled: false socket_mode_enabled: false token_rotation_enabled: false is_mcp_enabled: false ``` This manifest configures: - `display_information.name` and `features.bot_user.display_name`: Set your agent's name in Slack. You can update it at any time. Remember to reinstall the app after changing names or permissions. - `app_home.messages_tab_enabled` and `app_home.messages_tab_read_only_enabled`: Enable direct messages from the Slack app's **Messages** tab. - `always_online`: Shows the Slack bot user as always available. - `oauth_config.scopes.bot`: Grants permission to post and read messages in channels where the bot is present. It also covers mentions and direct messages, together with user lookup. - `event_subscriptions`: Tells Slack which message events to send to the webhook. - `interactivity`: Enables interactive cards and tells Slack where to send card actions. After the app is created, open **Install App**, select **Install to Workspace**, and approve the requested scopes. ## Set Slack credentials Set the Slack credentials in Mastra so it can verify Slack requests and send messages back to Slack. In the Slack app settings, copy these values: - **Basic Information** > **App Credentials** > **Signing Secret** - **OAuth & Permissions** > **Bot User OAuth Token** Set them in your Mastra environment: ```bash SLACK_SIGNING_SECRET=your-signing-secret SLACK_BOT_TOKEN=xoxb-your-bot-token ``` Mastra reads these environment variables automatically. ## Configure the webhook route Slack sends channel activity to Mastra through webhooks. A webhook is an HTTP endpoint Slack calls when something happens, such as a new message, a mention, or a user selecting an interactive card. Mastra automatically registers a Slack webhook route for your agent: ```text /api/agents/<YOUR-AGENT-ID>/channels/slack/webhook ``` Build the webhook URL from your public Mastra server URL and the generated route: ```text https://<YOUR-PUBLIC-URL>/api/agents/<YOUR-AGENT-ID>/channels/slack/webhook ``` Slack can't send events to `localhost`. For local development, keep the Mastra dev server running and expose `http://localhost:4111` with a tunnel before you save the request URL in Slack. Use a tunnel such as `cloudflared` or `ngrok` for local development: **npm**: ```bash npx cloudflared tunnel --url http://localhost:4111 ``` **pnpm**: ```bash pnpm dlx cloudflared tunnel --url http://localhost:4111 ``` **Yarn**: ```bash yarn dlx cloudflared tunnel --url http://localhost:4111 ``` **Bun**: ```bash bun x cloudflared tunnel --url http://localhost:4111 ``` Use the generated tunnel host as `<YOUR-PUBLIC-URL>`, for example: ```text https://abc123.trycloudflare.com/api/agents/your-agent/channels/slack/webhook ``` Update the request URLs in Slack: 1. In the Slack app settings, open **Event Subscriptions**. 2. Replace **Request URL** with the final webhook URL. 3. Select **Save Changes**. 4. Open **Interactivity & Shortcuts**. 5. Replace **Request URL** with the same webhook URL. 6. Select **Save Changes**. 7. If Slack asks you to reinstall the app, open **OAuth & Permissions** and select **Reinstall to Workspace**. ## Try it in Slack Open a direct message with the Slack bot user and send a message. Direct messages work because the manifest includes the `message.im` event and `im:*` scopes. To use the agent in a channel, invite the Slack bot user first: ```text /invite @your-bot-name ``` Mention the bot in the channel: ```text @your-bot-name What can you help me with? ``` The agent responds in the thread. Response content depends on the model, instructions, memory, and tools configured on the agent. ## Authentication The Slack adapter has no built-in user allowlist. Once the app is installed, anyone in the workspace can talk to the agent by sending it a direct message or mentioning it in a channel where it's a member. Slack verifies each request with the signing secret, and Mastra runs the agent for every valid message the webhook receives. The main mechanism for controlling access is channel membership. The bot only receives events from direct messages and from channels it has been invited to, so the set of channels the bot belongs to defines who can reach it. Keep the bot out of channels where it shouldn't respond, and remove it from a channel to cut off access. For finer control, gate on the sender's identity. Every request carries the sender's Slack user ID in the channel [request context](#request-context), so you can allow or deny specific users in an input processor or tool before the agent acts. ### Server authentication The Slack webhook route is exempt from Mastra's [server authentication](https://mastra.ai/docs/server/auth). Slack can't send a bearer token, so Mastra registers the channel webhook as a public route and verifies each request with the Slack signing secret instead. This holds even when you enable a provider like [`MastraAuthSimple`](https://mastra.ai/docs/server/auth/simple-auth): the rest of your API stays protected, but the webhook route relies on the signing secret rather than your server auth. Keep `SLACK_SIGNING_SECRET` set so the adapter can reject requests that Slack didn't sign. ### External channels Shared channels ([Slack Connect](https://slack.com/connect)) let people from other workspaces join a conversation. If a workspace member adds the bot to a shared channel, everyone in that channel can talk to the agent, including external members outside your organization. Anyone who can reach the agent can also reach the tools and data it has access to. Treat adding the bot to a shared or external channel as granting those participants access to the agent. Before you do, confirm the agent's tools and data are safe to expose to outside members, and gate on the sender's user ID when you need to restrict who the agent responds to. ## Request context On every message, Mastra places a channel context object on the [request context](https://mastra.ai/docs/server/request-context) under the `channel` key. It carries the sender's Slack display name and user ID, the bot's own identity, and details about where the message came from. Read it from an input processor or a tool to identify the user or branch on the conversation type: ```typescript import { createTool } from '@mastra/core/tools' import type { ChannelContext } from '@mastra/core/channels' import { z } from 'zod' export const whoami = createTool({ id: 'whoami', description: 'Return the Slack identity of the current user', inputSchema: z.object({}), execute: async (_input, context) => { const channel = context?.requestContext?.get('channel') as ChannelContext | undefined return { platform: channel?.platform, userId: channel?.userId, userName: channel?.userName, isDM: channel?.isDM, } }, }) ``` The channel context includes: - `botMention`, `botUserId`, and `botUserName`: The bot's own identity on Slack. - `channelId` and `threadId`: The Slack channel and thread the message arrived on. - `isDM`: Whether the message is a direct message. - `platform`: The platform identifier, `slack` for this adapter. - `userId` and `userName`: The sender's Slack user ID and display name. Mastra also turns this context into a short system message. The agent learns the platform and its own identity, plus whether the conversation is a direct message or a public channel. See [thread context](https://mastra.ai/docs/capabilities/channels/overview) in the channels overview for how to change that behavior. ## Production deployment When you deploy the Mastra server, update both request URLs in the Slack app settings to the production webhook URL. The tunnel URL used for local development is temporary and changes when the tunnel restarts. Channels on serverless platforms may need `waitUntil` and shared pub/sub configuration so background responses and thread leases work across short-lived instances. See [serverless deployment](https://mastra.ai/docs/capabilities/channels/overview) in the channels overview. ### Idle servers Platform servers scale down to idle when they aren't receiving traffic, and that's fine for Slack. The next event, such as a mention or direct message, wakes the server by delivering its webhook request, and the server resumes handling requests. The first response after the server has been idle can take a little longer while it starts up, which is expected. Slack expects a `200` acknowledgement within 3 seconds and retries the event up to three times when delivery fails or times out, so a very slow cold start may take a retry before the agent responds. Subsequent messages respond at normal speed while the server stays warm. ## Related - [Channels overview](https://mastra.ai/docs/capabilities/channels/overview) - [More](https://mastra.ai/docs/capabilities/channels/other-adapters) - [Channels reference](https://mastra.ai/reference/agents/channels) - [Deployment overview](https://mastra.ai/docs/deployment/overview)