- Studio
- Managed Agents
- Examples
Build a Slack feedback triage bot
Build a Slack feedback triage bot
Build a Slack bot that watches one channel, identifies actionable product feedback, searches Linear for duplicates, and creates or comments on issues. Top-level messages are processed automatically. Replies continue the same conversation only when someone mentions the bot.
You will run both the agent and Slack bot locally:
Slack channel
↓ Socket Mode
bot.py
↓ the agent's session
agent, served on your computer (`agents serve`)
↓ Linear MCP server, authenticated with a Linear API key
Linear
agents serve runs the agent on your computer and registers it with Mistral. bot.py listens to Slack and opens one Mistral session for each Slack thread.
Demonstrates: connectors and MCP, structured output, turns (idempotency keys, a message sent while a turn runs), following a session's events, stopping a turn, serving an agent.
Run (after the setup below), from the example's folder: uv run --frozen --env-file .env python bot.py
What the bot does
- Reviews every new top-level message in one Slack channel.
- Silently ignores irrelevant messages.
- Asks one short question when feedback is too vague.
- Classifies specific feedback as a question, idea, bug, or feature request.
- Searches one Linear project before creating anything.
- Adds useful evidence to a strong duplicate instead of creating another issue.
- Creates one Triage issue for new actionable feedback.
- Shows a temporary status while the agent works.
- Keeps follow-up context inside the Slack thread.
- Responds to thread replies only when someone mentions the bot.
The Slack bot's code
The example has two projects: the agent in agent/, and the Slack bot at the root.
File | What it shows |
|---|---|
| agent/main.py | The agents.Agent the CLI runs, with the Linear MCP server and the TriageReply answer format |
| agent/instructions.py | The full triage instructions: classification order, duplicate handling, safety rules |
| agent/check_linear_mcp.py | A read-only validation run that searches Linear without writing |
| agent_client.py | Resolving the agent and reading a turn's TriageReply |
| bot.py | Slack handlers: one session per thread stored in threads.json, mention gating, buffered context, stop |
The example's README.md has the full setup and test script.
The agent sets its answer format, TriageReply, so the model is asked for it:
from instructions import INSTRUCTIONS
from pydantic import BaseModel
from mistralai import agents
class TriageReply(BaseModel):
"""The answer to each message. The bot reads it with the same `TriageReply` class."""
respond: bool
message: str
# Replace `your-id` with a unique lowercase identifier, such as your GitHub handle,
# so the served and deployed names cannot collide with anyone else's.
# The bot's AGENT_NAME must match this name exactly.
agent = agents.Agent(
model="mistral-medium-latest",
name="feedback-triage-your-id-local",
instructions=INSTRUCTIONS,
output_type=TriageReply,
mcps={
"linear": agents.RemoteMCP(
url="https://mcp.linear.app/mcp",
auth_header_env_vars={"Authorization": "LINEAR_MCP_TOKEN"},
)
},
)
The bot reads each completed turn's answer with the same TriageReply class:
import logging
from pydantic import BaseModel
from mistralai import agents
logger = logging.getLogger(__name__)
class TriageReply(BaseModel):
"""The agent's answer to each message: the same class as in `agent/main.py`."""
respond: bool
message: str
def connect(agent_name: str) -> agents.Agent:
return agents.Agent.load_from(agent_name=agent_name)
async def read_reply(session: agents.Session, turn_id: str) -> str | None:
"""The reply to post for a completed turn, or None when the agent chose not to respond."""
match await session.turn(turn_id).result(output_type=TriageReply):
case agents.Completed(output=TriageReply(respond=False)):
return None
case agents.Completed(output=TriageReply(message=message)):
return message
case state:
# No TriageReply: an answer in another shape, or a turn that reached its iteration limit.
logger.warning("Turn %s gave no triage reply: %r", turn_id, state)
return "❌ I couldn’t complete the triage. Please try again."
Each Slack message reaches the session with its timestamp as the idempotency key. It starts a turn, or steers the running one:
# Starts a turn, or steers the running one. Slack's timestamp is the idempotency key,
# so the message reaches the agent once.
turn = await agent.session(thread["session_id"]).send_message(
f"{input_type}\n\n{source}{message}", idempotency_key=event["ts"]
)
if turn.started:
thread["last_turn_id"] = turn.id
thread["status"][turn.id] = {"ts": status["ts"], "top_level": not is_follow_up}
One follower per thread posts the answer of each turn. It keeps the id of the last event it posted, so after a restart or a dropped connection it reads on from there. A session that has ended raises one of the SESSION_GONE errors:
# A session ends after a time without turns, or when it reaches its lifetime.
SESSION_GONE = (agents.SessionTerminatedError, agents.SessionNotFoundError)
async def post_answers(thread_ts: str) -> None:
"""Post the answer of each turn of the thread's session, from the last event posted on."""
thread = threads[thread_ts]
session = agent.session(thread["session_id"])
while thread_ts in threads:
try:
async for event in session.iter_events(after=thread["cursor"]):
if isinstance(event, agents.TurnEnded):
async with locks[thread_ts]:
status = thread["status"].get(event.state.turn_id)
await post_answer(session, thread_ts, event, status)
if thread_ts not in threads:
return
thread["status"].pop(event.state.turn_id, None)
thread["cursor"] = event.id
save()
# The session has ended: a later mention gets NO_SESSION.
forget(thread_ts)
except SESSION_GONE:
forget(thread_ts)
except Exception:
# The connection dropped (ObservationLost), or posting failed. Nothing is missed:
# read again after the last event posted, and post that answer again.
app.logger.exception("Following thread %s failed; reading again", thread_ts)
await asyncio.sleep(10)
Prerequisites
You need:
- Python 3.12 and uv.
- A Mistral API key whose user has a workspace role with Workflows access, such as Developer: see Deploy. agents serve requires it.
- A Linear API key that can read, create issues, and create comments on the target team.
- Permission to create and install a Slack app in your workspace.
- A public Slack channel for testing.
1. Create the Linear API key
The agent reaches Linear through Linear's hosted MCP server rather than a Mistral Studio connector, because the key is a fixed credential the agent always runs as. Create one in Linear under Settings → Security & access → Personal API keys, scoped to the team you want to triage into.
It needs three permissions. Read and issue creation cover the common path; comment creation is what the duplicate path uses, and a key without it fails only once the agent finds a duplicate and tries to add evidence:
{"error":"auth_insufficient_scope","message":"Not allowed to access this Linear resource.","status":403}
Choose one Linear project and team for the agent, then set both values at the top of agent/instructions.py. The key may reach more projects than that one; the instructions pick the target, they do not restrict the key.
2. Create the Slack app
You need a Slack app with Socket Mode, two bot scopes and one event, its two tokens, and the ID of the test channel.
Set up the Slack app
Open Your Apps, select Create New App, then choose From scratch.
Use:
- App name: AgentsFeedbackBot
- Workspace: your test workspace
Enable Socket Mode
Open Socket Mode and enable it. Create an app-level token with the connections:write scope. Copy the token beginning with xapp-; Slack only shows it once.
Add bot permissions
Open OAuth & Permissions and add these bot token scopes:
- channels:history
- chat:write
Subscribe to messages
Open Event Subscriptions, enable events, and subscribe to this bot event:
- message.channels
Socket Mode carries the events, so you do not need a public request URL.
Install the app
Select Install to Workspace and complete the approval flow. Copy the bot token beginning with xoxb-.
If your organization reviews Slack apps, submit the app after its name, description, scopes, and event subscription are complete. Reinstall it whenever you change OAuth scopes.
Invite the bot to the test channel:
/invite @AgentsFeedbackBot
To find the channel ID in Slack desktop or web:
1.
Open the channel.2.
Select the channel name in the conversation header.3.
Open the About tab.4.
Scroll to the bottom and copy the channel ID.
Slack channel IDs look like C0123456789.
Keep both Slack tokens secret. Anyone with them can operate the app.
3. Set up and inspect the agent
From the agent/ project, copy .env.example to .env and fill in both keys:
MISTRAL_API_KEY=...
LINEAR_MCP_TOKEN="Bearer lin_api_..."
LINEAR_MCP_TOKEN holds the complete Authorization header value, scheme included, because auth_header_env_vars maps a header name to the variable holding that header. Keep the quotes: the space after Bearer ends the value without them, and --env-file reports Failed to parse environment file.
Then install and inspect:
cd agent
uv sync
uv run --frozen --env-file .env agents info
agents info lists the linear MCP server with its host. It shows that the server is declared, not that the agent can reach it. The next step checks that.
4. Validate Linear without writing
Confirm the agent can reach Linear and search the target project:
uv run --frozen --env-file .env python check_linear_mcp.py
Continue when it returns issues from the intended project, with nothing created, updated, or deleted.
5. Serve the agent
bot.py runs separately from the agent, so it cannot use the in-process Agent object. Start the agent with agents serve so the bot can open sessions against it:
uv run --frozen --env-file .env agents serve
The command registers the agent with Mistral Workflows and runs it on your computer. Keep this terminal open.
Mistral identifies served agents by name. The example uses your-id as a placeholder: replace it with a unique lowercase identifier, such as your GitHub handle, everywhere it appears. The bot's AGENT_NAME must match the agent name exactly.
Do this before serving. If someone else already holds the name, agents serve stops before the agent starts, exits 1, and prints the control plane's reason, such as:
Cannot serve agent: registration failed at https://...: the name feedback-triage-your-id-local is already bound to another workflow or deployment
The worker cannot receive sessions until it is registered.
6. Run the bot
Back in the example root, copy .env.example to .env and fill in both Slack tokens, the channel ID, your Mistral API key, and the agent name:
uv sync
uv run --frozen --env-file .env python bot.py
Continue when it prints:
Listening to Slack channel C0123456789 as bot user U0123456789...
The Slack bot needs its own MISTRAL_API_KEY because it calls Mistral directly to start sessions: agents serve runs the agent, but the bot still authenticates when it opens and advances sessions.
7. Test the complete flow
Test silent handling
Post an irrelevant top-level message:
Has anyone seen the HDMI adapter?
🧠 Reviewing this feedback… should appear briefly and then disappear.
Test clarification and buffered context
Post:
The Managed Agents setup is confusing.
The bot should ask one short clarification question without searching Linear.
Reply without mentioning the bot:
Some tools are not disabled as expected.
The bot should remain silent but retain the message. Send a second thread reply containing only:
@AgentsFeedbackBot
The bot should combine the buffered detail with the existing session and continue triage.
Test a duplicate
Use genuine feedback that matches an existing issue. The agent should search the target project, add useful new evidence once, and return the existing issue identifier and link.
This test writes a real Linear comment. Do not use synthetic evidence in a production backlog.
Test a new request
Use genuine, specific feedback with no existing match. The agent should create one Triage issue, include the Slack thread link, and return the new Linear URL.
Test thread gating
After the bot responds, send a normal thread reply without mentioning it. Nothing should happen. Then mention @AgentsFeedbackBot in the thread. The same Mistral session should answer.
Test stop
While the bot is still working on a thread, send @AgentsFeedbackBot stop in that thread. The status should change to ⏹️ Stopped. When no turn is running, the bot replies Nothing is running.
Deploy the agent
The agent reads its Linear credential from LINEAR_MCP_TOKEN in the environment it runs in. When Mistral runs the agent, it gets that variable from a workspace secret you bind at deploy time.
First, create a secret holding the same complete header value as your .env (Bearer lin_api_...) at console.mistral.ai → Secrets. Then deploy from agent/ and bind the variable to it:
uv run --frozen --env-file .env agents deploy . --name feedback-triage-your-id \
--secret-binding LINEAR_MCP_TOKEN=secret:workspace:linear-triage-key
Without the binding, the deploy warns and the deployed agent refuses to start:
MCP server 'linear' reads its auth headers from LINEAR_MCP_TOKEN, which is not set in the worker environment.
Then set the bot's AGENT_NAME to feedback-triage-your-id. See Pass secrets for how bindings work.
Session behavior
Each top-level Slack message creates one Mistral session. The root Slack timestamp maps that thread to its session:
Top-level message → create session → triage
Thread reply without mention → buffer context → stay silent
Thread reply with mention → send to the session → a new turn, or steers the running one
bot.py stores each thread's session id, its buffered replies and the last session event it posted in threads.json. For each thread it follows the session's events, so a restarted bot picks up every stored thread and posts the answers it missed. It also stores the Slack messages it handled in each thread and skips one that Slack delivers again. Each message reaches the agent with its Slack timestamp as the idempotency key, so even two copies of a thread reply handled at once start one turn. When a thread's session ends, the bot forgets the thread.
The agent answers in a TriageReply, set as output_type on the agent: respond and message. When respond is false on a top-level message, the bot removes its status and ends the session.
Security and limitations
Everyone who can post in the channel shares one Linear identity — the key in LINEAR_MCP_TOKEN. Scope that key when you create it, because it is the only real boundary here. The target project in instructions.py is a prompt instruction, and Linear's MCP server advertises its full tool surface regardless: the agent can see tools for deleting, merging, and administering, and only Linear's own scope check stops them. Anything the key can do, anyone in the channel can eventually get the agent to do.
A personal API key also attributes every issue and comment to the person who created it. Use a key belonging to a service account if you do not want the bot's writes showing up under your name.
- Everyone who can post in the configured public channel can trigger the agent.
- Tool restrictions are partly prompt-enforced because save_issue can create and update issues.
- threads.json is a local file: run one bot process per file.
- Text attachments, screenshots, and edited messages are ignored.
- The bot handles one configured channel and one Linear project.
- With agents serve, the bot and the agent both run on your computer. To have Mistral run the agent, see Deploy the agent.
For production, store the thread mappings in a database, and add user or channel allowlists, attachment handling, observability, and an integration layer that validates every Linear write independently of the model.
Inspect sessions in Mistral Studio
Sessions handled by an agent started with agents serve appear in Agent sessions in Mistral Studio. Open a session to review its messages, tool calls, and status.
Troubleshooting
uv run --frozen cannot find uv.lock
Run uv sync once in that project, then retry the command.
Failed to parse environment file on LINEAR_MCP_TOKEN
Quote the value. The space after Bearer truncates it otherwise.
agents serve refuses to start naming LINEAR_MCP_TOKEN
MCP server 'linear' reads its auth headers from LINEAR_MCP_TOKEN, which is not set in the worker environment. Export each in your shell, or put it in .env and start the worker with `uv run --env-file .env`.
The variable is read where the agent runs, so it has to exist in the terminal running agents serve, not just in the bot's.
Linear returns auth_insufficient_scope
The key is missing a permission. Read plus issue creation is not enough: the duplicate path comments on an existing issue, so the key also needs comment creation on that team.
agents serve says the name is already bound
The agent name is already registered by someone else. Replace your-id everywhere with a unique identifier. A successful start ends with Press Ctrl+C to stop.
agents serve cannot register the agent
Check that MISTRAL_API_KEY is valid and that its user has a workspace role with Workflows access (see Deploy for the roles). A key that can call a model may still lack permission to register the agent.
The bot does not answer
Confirm that:
- agents serve is still running.
- bot.py is still running.
- AGENT_NAME exactly matches the served agent name.
- The app is invited to the channel in SLACK_TARGET_CHANNEL_ID.
- Socket Mode and message.channels are enabled.
- The bot token and app token start with xoxb- and xapp- respectively.
The bot ignores a thread reply
That is expected unless the reply mentions @AgentsFeedbackBot. Unmentioned replies are buffered only while the bot has an active session for that thread.
The bot says it no longer has a session for the thread
The thread is not in threads.json: the bot started it before the file was deleted, ended its session because the message needed no answer, or the session ended on its own, after a time without turns or at its lifetime limit. A session that ends during a turn shows this message as the turn's answer. Repost the feedback as a new top-level message.
The agent describes future actions instead of performing them
Restart agents serve after changing agent/instructions.py, then begin a fresh Slack thread. An existing session may still reflect the previous agent definition.
The temporary status remains or changes to an error
Inspect both terminals. The status is updated only after the Mistral turn and any Linear MCP calls complete. A turn runs until it ends or you stop it: mention the bot with stop in the thread.
Resources and next steps
- Connectors and MCP explains Mistral Studio connectors and custom MCP servers, and when a static credential means reaching for an MCP source instead.
- Sessions explains the conversation history and event stream used by bot.py.
- Run modes compares running the agent in your process with deploying it with Studio (self-hosted or Mistral-managed).
- Agent documents the agents.Agent the CLI loads from main.py.