> ## Documentation Index
> Fetch the complete documentation index at: https://cadenya.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Building a Slack agent

> Connect a Slack app to a Cadenya Agent with Bolt for JavaScript, webhooks, and the Cadenya SDK.

This guide connects a Slack app to a Cadenya Agent. It takes about 15 minutes.

When you finish, the app does three things:

* It answers DMs and @mentions with your Agent.
* It shows each tool call in the thread and updates the status as the call runs.
* It asks for approval with buttons before a tool runs.

The code is on GitHub: [cadenya/slack-ai-agents-example](https://github.com/cadenya/slack-ai-agents-example). It uses [Bolt for JavaScript](https://docs.slack.dev/tools/bolt-js/) and the `@cadenya/cadenya` SDK.

![Slack thread where the Cadenya Agent replies to a request for a contact card. Three collapsed plans read Used 8 tools, Used 2 tools, and Used 3 tools. The last plan is expanded to show three GenerateFake calls. A code block with the contact card and thumbs up and down buttons follow.](https://mintcdn.com/cadenya/1Efp4rJOF9eYqoNz/images/guides/slack-ai-agents/slack-ai-agent-tool-calls.png?fit=max\&auto=format\&n=1Efp4rJOF9eYqoNz\&q=85\&s=ef321f63a4615302d46c6a0a7743e519)

The Agent's reply in a Slack thread. Each step of the agent loop shows its tool calls as a plan, and the final answer has feedback buttons.

## Prerequisites

You need:

* A Cadenya account.
* The Cadenya CLI. The next section installs it.
* A Slack workspace where you can install apps. Slack offers free [developer sandboxes](https://docs.slack.dev/tools/developer-sandboxes/).
* The [Slack CLI](https://docs.slack.dev/tools/slack-cli/). Log in with `slack login`.
* Node.js 22 or later.
* [ngrok](https://ngrok.com/download), or another tunnel.

## Install the Cadenya CLI

Install the CLI with Homebrew:

```bash theme={null}
brew install cadenya/tools/cadenya
```

The [CLI guide](https://cadenya.com/docs/guides/the-basics/cli.md#install-the-cli) lists the other install options. Then log in and choose a workspace:

```bash theme={null}
cadenya auth login
cadenya workspaces list
cadenya config set workspace-id development
```

Replace `development` with the external ID of your workspace.

## How it works

Slack and Cadenya do not connect to each other. Your app sits between them. It sends Slack messages to Cadenya, and it posts Cadenya's webhook events to Slack.

```mermaid theme={null}
sequenceDiagram
  participant Slack
  participant App as Your Bolt app
  participant Cadenya
  Slack->>App: Message in a thread
  App->>Cadenya: Create or continue the Objective
  Note over App: The call returns right away
  Cadenya-->>App: Webhook: toolApprovalRequested
  App->>Slack: Plan task, plus Approve and Deny buttons
  Slack->>App: Click
  App->>Cadenya: ApproveToolCall
  Cadenya-->>App: Webhooks: toolCalled, toolResult
  App->>Slack: Plan task: complete
  Cadenya-->>App: Webhook: assistantMessage
  App->>Slack: Reply in the thread
```

**One Slack thread is one [Objective](https://cadenya.com/docs/guides/the-basics/objectives.md).** The app stores the link between them on the Objective:

| Field | Value | Used to find |
| - | - | - |
| `metadata.externalId` | `slack-<team>-<channel>-<thread_ts>` | The Objective for a Slack thread |
| `metadata.labels` | `slack_team`, `slack_channel`, `slack_thread_ts`, `slack_user` | The Slack thread for a webhook |

Every webhook includes the Objective's labels. The app reads the thread from them, so it needs no lookup and no database.

## Set it up

**1. Clone the example**

```bash theme={null}
git clone https://github.com/cadenya/slack-ai-agents-example.git
cd slack-ai-agents-example
npm install
cp .env.sample .env
```

**2. Create the Agent**

These commands create a Tool Set, an Agent, and a variation, then publish the Agent. The Tool Set uses Cadenya's free Faker MCP server. It requires approval for every call, so you can try the approval buttons.

Set `MODEL_ID` to a model from `cadenya models list`:

```bash theme={null}
MODEL_ID=your-model-id

cadenya tool-sets create \
  --name "Faker MCP" \
  --external-id faker \
  --description "Generates fake names, addresses, and other sample data" \
  --adapter mcp \
  --mcp-url https://free.cadenya.com/faker-mcp \
  --mcp-tool-approvals always --mcp-tool-approvals-always

cadenya agents create \
  --name "Slack agent" \
  --external-id slack-agent \
  --description "Answers questions in Slack threads"

cadenya agents variations create external_id:slack-agent \
  --name Default \
  --external-id default \
  --model-id "$MODEL_ID" \
  --system-prompt-template "You answer questions in Slack threads. Keep replies short. Use the Faker tools for sample data, and never invent it yourself." \
  --assignment '{"type": "toolSetId", "toolSetId": "external_id:faker"}'

cadenya agents publish external_id:slack-agent
```

If you already have a published Agent, skip this step. Use that Agent's ID for `CADENYA_AGENT_ID` in a later step.

**3. Set the Agent's webhook URL**

Cadenya sends webhooks to a public URL. The app listens on port `3210`, so start a tunnel to that port:

```bash theme={null}
ngrok http 3210
```

Copy the forwarding URL and set it as the Agent's webhook URL. **Add `/webhooks/cadenya` to the end.**

```bash theme={null}
cadenya agents update external_id:slack-agent \
  --webhook-events-url https://your-tunnel.ngrok-free.dev/webhooks/cadenya
```

**4. Fill in .env**

The app needs four values:

```bash .env theme={null}
CADENYA_API_KEY=your-api-key
CADENYA_WORKSPACE_ID=your-workspace-id
CADENYA_AGENT_ID=external_id:slack-agent
CADENYA_WEBHOOK_SECRET=whsec_your-signing-key
```

Create an API key with only the `objectives:manage` scope. This command prints the token. Cadenya shows it only when you create the key, so save it now.

```bash theme={null}
cadenya workspaces list   # find your workspace ID

cadenya api-keys create \
  --name "Slack agent" \
  --workspace-assignment workspace-id=your-workspace-id \
  --permission objectives:manage \
  --display json | jq -r '.spec.token'
```

Copy the webhook signing key from [**Account Admin**](https://app.cadenya.com/account/webhooks). Every Agent in the account uses the same key.

**5. Run it**

```bash theme={null}
slack run
```

The first run creates the Slack app from `manifest.json` and asks which workspace to install it in. The app uses [Socket Mode](https://docs.slack.dev/apis/events-api/using-socket-mode/), so Slack does not need a public URL.

You should see:

```
[INFO]  bolt-app Slack agent is running! Cadenya webhooks: http://localhost:3210/webhooks/cadenya
```

**6. Send a message**

DM the app, or @mention it in a channel:

```
Can you generate a fake name for me?
```

The thread shows a plan named **Working on it** and an approval request with **Approve** and **Deny** buttons:

![Slack thread where the Cadenya Agent shows a plan titled Working on it, then a message that reads The agent wants to run GenerateCurseWord and needs approval, the tool arguments, and green Approve and red Deny buttons.](https://mintcdn.com/cadenya/1Efp4rJOF9eYqoNz/images/guides/slack-ai-agents/slack-ai-agent-tool-calls-approval.png?fit=max\&auto=format\&n=1Efp4rJOF9eYqoNz\&q=85\&s=1bd83f27dfb5adfc001eeb3eccba3cc1)

An approval request in the thread. This one is for the Faker server's GenerateCurseWord tool.

Click **Approve**. The task in the plan changes to complete, and the Agent's reply appears in the thread.

Some models call `GetFakerOptions` first. If that happens, approve that call too.

To continue the conversation, reply in the thread. The app sends each reply to the same Objective.

## How the code works

Most of the logic is in four files.

### Send a Slack message to Cadenya

The app builds an external ID from the Slack thread. If the thread already has an Objective, the app continues it. Otherwise, the app creates one. This is a shortened version of `cadenya/thread.js`:

```js cadenya/thread.js theme={null}
const externalId = `slack-${teamId}-${channelId}-${threadTs}`;

if (objective && !isTerminal(objective)) {
  await cadenya.objectives.continue(objective.metadata.id, { message: text, enqueue: true });
  return;
}

await cadenya.objectives.create({
  agentId: process.env.CADENYA_AGENT_ID,
  firstUserMessage: text,
  metadata: {
    externalId,
    labels: { slack_team: teamId, slack_channel: channelId, slack_thread_ts: threadTs, slack_user: userId },
  },
});
```

A few details:

1. **Neither call waits for the Agent.** Slack expects a response to each event within 3 seconds. An Agent that calls tools takes longer. The reply arrives later, on a webhook.
2. Slack can send the same event twice. The second create fails with `409` because the external ID exists, and the app ignores that error.
3. **You can't reuse an external ID, even after its Objective ends.** If someone replies in a thread whose Objective has ended, the app creates a new Objective. Its external ID is `<external ID>-<message ts>`, and the app finds it by label.
4. `enqueue: true` queues a message that arrives while the Agent is still working.

### Receive webhooks

Bolt serves the webhook endpoint as a [custom route](https://docs.slack.dev/tools/bolt-js/concepts/custom-routes/). The route verifies the signature, then reads the Slack thread from the labels:

```js cadenya/webhook-route.js theme={null}
const event = await cadenya.webhooks.unwrap(rawBody, req.headers); // throws on a bad signature

const { objective, rootObjective, objectiveEvent } = event.data;
const { slack_team, slack_channel, slack_thread_ts, slack_user } = (rootObjective ?? objective).labels;
```

To see what Cadenya sends, open the ngrok inspector at `http://localhost:4040`. It lists each webhook with its headers and body, and it can replay one. This `tool_result` webhook shows the Slack labels and the external ID on `data.objective`:

![ngrok inspector showing a POST to /webhooks/cadenya. The JSON body has the type objective\_event.tool\_result, and its data.objective has labels for slack\_channel, slack\_team, slack\_thread\_ts, and slack\_user, plus an externalId built from the same values.](https://mintcdn.com/cadenya/1Efp4rJOF9eYqoNz/images/guides/slack-ai-agents/slack-ai-agent-ngrok-tool-call.png?fit=max\&auto=format\&n=1Efp4rJOF9eYqoNz\&q=85\&s=5deafbc7aca1d0f6b5e27bea07b33144)

A tool result webhook in the ngrok inspector. The Objective's labels name the Slack team, channel, thread, and user.

A few details:

1. `unwrap` needs the raw request body. Read the body before any code parses it as JSON.
2. Cadenya retries a failed delivery. The route stores each `webhook-id` it has processed and skips repeats.
3. A webhook from a sub-agent includes `rootObjective`. The app uses its labels, so the event goes to the thread that started the work.

The [webhooks guide](https://cadenya.com/docs/guides/the-basics/webhooks.md) describes the payload and every event type.

### Show tool calls as a plan

Events from the same step of the agent loop have the same `iterationId`. One step is an assistant message plus the tool calls it requested. The app uses `iterationId` to group events into one Slack message.

For each iteration, the app starts a Slack message with [`chat.startStream`](https://docs.slack.dev/reference/methods/chat.startStream/) in `plan` mode. Then it appends a chunk for each webhook. This is a simplified version of `cadenya/thread-renderer.js`:

```js cadenya/thread-renderer.js theme={null}
const reply = slack.chatStream({
  channel: slack_channel,
  thread_ts: slack_thread_ts,
  recipient_team_id: slack_team, // Slack requires both recipients in channels
  recipient_user_id: slack_user,
  task_display_mode: 'plan',
});

const data = objectiveEvent.data;

if (data.type === 'toolCalled') {
  const { toolCallId, llmToolName } = data.toolCalled;
  await reply.append({
    chunks: [{ type: 'task_update', id: toolCallId, title: llmToolName, status: 'in_progress' }],
  });
}
if (data.type === 'toolResult') {
  const { toolCallId, llmToolName } = data.toolResult;
  await reply.append({
    chunks: [{ type: 'task_update', id: toolCallId, title: llmToolName, status: 'complete' }],
  });
}
if (data.type === 'assistantMessage' && data.assistantMessage.content) {
  await reply.append({ chunks: [{ type: 'markdown_text', text: data.assistantMessage.content }] });
}
```

Slack shows each `task_update` as a task in a [plan block](https://docs.slack.dev/reference/block-kit/blocks/plan-block/). The task ID is the tool call ID, so a second update changes the status of the same task.

When every tool call in the iteration has finished, the app stops the stream. The final answer also gets feedback buttons.

The app uses a Slack stream because [`chat.appendStream`](https://docs.slack.dev/reference/methods/chat.appendStream/) lets several webhooks add to one message. The reply text still arrives all at once. Cadenya sends text deltas on the [event stream](https://cadenya.com/docs/guides/the-basics/objectives.md#stream-new-events), not on webhooks.

A few details:

1. **Webhooks for one Objective can arrive at the same time, or out of order.** For example, a `toolCalled` webhook can arrive before the `assistantMessage` that requested the call. The app processes one event at a time for each Objective. It never changes a finished task back to in progress.
2. Slack closes a stream after 10 minutes. An approval can take longer than that. If the stream has closed, the app continues in a new message.
3. Tool calls from a sub-agent do not appear in the plan. Its approval requests and errors still appear in the thread.

### Approve or deny a tool call

Slack has no built-in approval step. The app posts [Block Kit](https://docs.slack.dev/block-kit/) buttons and puts the Objective ID and tool call ID in each button's `value`. When someone clicks a button, the handler reads the IDs back:

```js listeners/actions/tool-approval-buttons.js theme={null}
const { objectiveId, toolCallId } = JSON.parse(action.value);

if (action.action_id === 'tool_approve') {
  await cadenya.objectives.approveToolCall(objectiveId, toolCallId);
} else {
  await cadenya.objectives.denyToolCall(objectiveId, toolCallId, {
    memo: `Denied in Slack by <@${userId}>. Do not retry this call without asking first.`,
  });
}
```

The Agent reads the `memo` when a call is denied, so write it as an instruction to the model.

The feedback buttons work the same way. A click calls `objectives.createFeedback` with a score of `1` or `-1`. Cadenya uses [feedback](https://cadenya.com/docs/guides/the-basics/objectives.md#objective-feedback) to choose between variations.

## Let the Agent act in Slack

The Faker tools run on a remote server. A [client tool](https://cadenya.com/docs/guides/the-basics/tool-sets.md#client-tools) runs in your app instead. Your app has the Slack token, so a client tool can call the Slack API.

The example defines one client tool, `add_emoji_reaction`, in `cadenya/client-tools.js`. The app passes the definition to `objectives.create`:

```js theme={null}
clientTools: {
  definitions: [{
    name: 'add_emoji_reaction',
    description: "Add an emoji reaction to the user's latest Slack message, such as `tada` or `eyes`.",
    parameters: {
      type: 'object',
      properties: { emoji_name: { type: 'string', description: 'The emoji name without colons.' } },
      required: ['emoji_name'],
    },
  }],
}
```

When the Agent calls the tool, the app receives a `toolCalled` webhook. The app calls Slack's `reactions.add`, then returns the result with `objectives.setToolCallContent`.

You can add your own client tools the same way. For example, a tool can pin a message or look up a user. A client tool can do anything your bot token allows.

## Before you deploy

The example is small on purpose. Change three things before you run it in production:

1. **Use a stable URL.** Host the app at a permanent address and update the Agent's webhook URL. You can keep Socket Mode, unless you plan to list the app in the Slack Marketplace. The Marketplace requires HTTP.
2. **Store state outside the process.** The app keeps two things in memory: the `webhook-id` values it has processed, and the open Slack message for each iteration. If you run more than one process, move both to a shared store. Use a unique constraint on `webhook-id`, and store each stream's `ts` by `iterationId`.
3. **Support more than one Slack workspace.** The app uses one bot token. To serve several workspaces, add Bolt's [OAuth installation store](https://docs.slack.dev/tools/bolt-js/concepts/authenticating-oauth/). Then choose the token with the `slack_team` label.

## See the conversation in Cadenya

As always, Cadenya stores the entire history of the conversation. Open the Objective in the dashboard to see each message, tool call, and approval on a timeline. The **External ID** in the details panel is the one the app built from the Slack thread.

![Cadenya dashboard showing an Objective timeline with user message, reasoning, assistant message, tool approval, tool called, and tool result events. The GenerateCurseWord call is expanded and marked Approved and Completed. A details panel shows the Slack external ID, the Slack agent, and execution stats.](https://mintcdn.com/cadenya/1Efp4rJOF9eYqoNz/images/guides/slack-ai-agents/slack-ai-agent-objective-details.png?fit=max\&auto=format\&n=1Efp4rJOF9eYqoNz\&q=85\&s=252686607bc1de68560fcce6b83c83f1)

The Objective for the approval example. The timeline shows the approval request, who approved it, and the tool call that followed.

## Where to go next

* To connect the Agent to your own API, create a [Tool Set](https://cadenya.com/docs/guides/the-basics/tool-sets.md).
* For suggested prompts, status, and streaming in Slack, see Slack's guide to [developing agents](https://docs.slack.dev/ai/developing-agents/).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.