Skip to content

Commit 8789d2e

Browse files
committed
feat: add Slack bot integration for kagent
Adds a production-ready Slack bot that provides a unified interface to interact with Kagent agents through Slack. Key features: - Socket Mode bot for @mentions and direct messages - Dynamic agent discovery and intelligent routing - Real-time streaming responses with human-in-the-loop approval - RBAC with Slack user group integration - Prometheus metrics and structured logging - Complete Kubernetes manifests (Deployment, HPA, PDB, RBAC) The bot integrates with Kagent's A2A protocol and supports all agent types (Declarative, BYO, etc.).
1 parent b1f142a commit 8789d2e

37 files changed

+2745
-0
lines changed

slackbot/.dockerignore

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Python
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
*.so
6+
.Python
7+
*.egg-info/
8+
dist/
9+
build/
10+
.venv/
11+
venv/
12+
env/
13+
14+
# Testing
15+
.pytest_cache/
16+
.coverage
17+
htmlcov/
18+
.tox/
19+
20+
# IDEs
21+
.vscode/
22+
.idea/
23+
*.swp
24+
*.swo
25+
*~
26+
27+
# Git
28+
.git/
29+
.gitignore
30+
31+
# CI/CD
32+
.github/
33+
34+
# Documentation
35+
*.md
36+
docs/
37+
38+
# Environment files (should be injected at runtime)
39+
.env
40+
.env.*
41+
42+
# Temporary files
43+
*.log
44+
*.tmp
45+
tmp/
46+
47+
# OS
48+
.DS_Store
49+
Thumbs.db
50+
51+
# Development tools
52+
Makefile
53+
mypy.ini
54+
.mypy_cache/
55+
.ruff_cache/
56+
57+
# Manifests (not needed in runtime image)
58+
manifests/

slackbot/.env.example

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Slack Configuration
2+
SLACK_BOT_TOKEN=xoxb-your-bot-token-here
3+
SLACK_APP_TOKEN=xapp-your-app-token-here
4+
SLACK_SIGNING_SECRET=your-signing-secret-here
5+
6+
# Kagent Configuration
7+
KAGENT_BASE_URL=http://localhost:8083
8+
KAGENT_TIMEOUT=30
9+
10+
# Server Configuration
11+
SERVER_HOST=0.0.0.0
12+
SERVER_PORT=8080
13+
14+
# Logging
15+
LOG_LEVEL=INFO
16+
17+
# Permissions (Phase 3)
18+
PERMISSIONS_FILE=config/permissions.yaml

slackbot/.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
.mypy_cache/
2+
.ruff_cache/
3+
.venv/
4+
*.pyc
5+
__pycache__/
6+
.env

slackbot/.python-version

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
3.13.7

slackbot/Dockerfile

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
FROM python:3.13-slim
2+
3+
# Set environment variables
4+
ENV PYTHONUNBUFFERED=1 \
5+
PYTHONDONTWRITEBYTECODE=1 \
6+
PIP_NO_CACHE_DIR=1 \
7+
PIP_DISABLE_PIP_VERSION_CHECK=1
8+
9+
WORKDIR /app
10+
11+
# Create non-root user early (files copied after will be owned by this user)
12+
RUN useradd -m -u 1000 appuser && \
13+
chown appuser:appuser /app
14+
15+
# Switch to non-root user for subsequent operations
16+
USER appuser
17+
18+
# Install dependencies first (better layer caching)
19+
COPY --chown=appuser:appuser pyproject.toml .
20+
RUN pip install --upgrade pip && \
21+
pip install .
22+
23+
# Copy application code
24+
COPY --chown=appuser:appuser src/ src/
25+
26+
# Copy default config (can be overridden with volume mount at runtime)
27+
COPY --chown=appuser:appuser config/ config/
28+
29+
# Health check
30+
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
31+
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')"
32+
33+
# Run application
34+
CMD ["python", "-m", "kagent_slackbot.main"]

slackbot/README.md

Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,257 @@
1+
# Kagent Slackbot
2+
3+
Production-ready Slack bot for the Kagent multi-agent platform. This bot provides a unified interface to interact with multiple AI agents through Slack, featuring dynamic agent discovery, intelligent routing, and rich Block Kit formatting.
4+
5+
## Features
6+
7+
- **Dynamic Agent Discovery**: Automatically discovers agents from Kagent via `/api/agents`
8+
- **Intelligent Routing**: Keyword-based matching to route messages to appropriate agents
9+
- **Streaming Responses**: Real-time updates for declarative agents with human-in-the-loop approval
10+
- **RBAC**: Slack user group integration with agent-level permissions
11+
- **Rich Formatting**: Professional Slack Block Kit responses with metadata
12+
- **Session Management**: Maintains conversation context across multiple turns
13+
- **Async Architecture**: Built with modern slack-bolt AsyncApp for high performance
14+
- **Production Ready**: Prometheus metrics, health checks, structured logging
15+
- **Kubernetes Native**: Complete K8s manifests with HPA, PDB, and security contexts
16+
17+
## Architecture
18+
19+
```
20+
User in Slack
21+
22+
@mention / slash command
23+
24+
Kagent Slackbot (AsyncApp)
25+
├── Agent Discovery (cache agents from /api/agents)
26+
├── Agent Router (keyword matching)
27+
└── A2A Client (JSON-RPC 2.0)
28+
29+
Kagent Controller (/api/a2a/{namespace}/{name})
30+
31+
┌─────────┬─────────┬──────────┐
32+
│ k8s │ security│ research │
33+
│ agent │ agent │ agent │
34+
└─────────┴─────────┴──────────┘
35+
```
36+
37+
## Quick Start
38+
39+
### Prerequisites
40+
41+
- Python 3.11+
42+
- Slack workspace with bot app configured
43+
- Kagent instance running and accessible
44+
45+
### Installation
46+
47+
1. Navigate to the slackbot directory:
48+
```bash
49+
cd /path/to/kagent/slackbot
50+
```
51+
52+
2. Create virtual environment and install dependencies:
53+
```bash
54+
python3 -m venv .venv
55+
source .venv/bin/activate
56+
pip install -e ".[dev]"
57+
```
58+
59+
3. Configure environment variables:
60+
```bash
61+
cp .env.example .env
62+
# Edit .env with your Slack tokens and Kagent URL
63+
```
64+
65+
Required environment variables:
66+
- `SLACK_BOT_TOKEN`: Bot user OAuth token (xoxb-*)
67+
- `SLACK_APP_TOKEN`: App-level token for Socket Mode (xapp-*)
68+
- `SLACK_SIGNING_SECRET`: Signing secret for request verification
69+
- `KAGENT_BASE_URL`: Kagent API base URL (e.g., http://localhost:8083)
70+
71+
### Running Locally
72+
73+
```bash
74+
source .venv/bin/activate
75+
python -m kagent_slackbot.main
76+
```
77+
78+
The bot will:
79+
1. Connect to Slack via Socket Mode (WebSocket)
80+
2. Start health server on port 8080
81+
3. Discover available agents from Kagent
82+
4. Begin processing messages
83+
84+
### Slack App Configuration
85+
86+
Your Slack app needs these OAuth scopes:
87+
- `app_mentions:read` - Receive @mentions
88+
- `chat:write` - Send messages
89+
- `commands` - Handle slash commands
90+
- `reactions:write` - Add emoji reactions
91+
92+
Required features:
93+
- **Socket Mode**: Enabled (no public HTTP endpoint needed)
94+
- **Event Subscriptions**: `app_mention`
95+
- **Slash Commands**: `/agents`, `/agent-switch`
96+
97+
## Usage
98+
99+
### Interacting with Agents
100+
101+
**@mention the bot** with your question:
102+
```
103+
@kagent show me failing pods
104+
```
105+
106+
The bot will:
107+
1. Extract keywords from your message ("pods" → k8s-agent)
108+
2. Route to the appropriate agent
109+
3. Respond with formatted blocks showing:
110+
- Which agent responded
111+
- Why that agent was selected
112+
- Response time and session ID
113+
114+
### Slash Commands
115+
116+
**List available agents**:
117+
```
118+
/agents
119+
```
120+
121+
Shows all agents with:
122+
- Namespace and name
123+
- Description
124+
- Ready status
125+
126+
**Switch to specific agent**:
127+
```
128+
/agent-switch kagent/security-agent
129+
```
130+
131+
All subsequent @mentions will use this agent until you reset.
132+
133+
**Reset to automatic routing**:
134+
```
135+
/agent-switch reset
136+
```
137+
138+
Returns to keyword-based agent selection.
139+
140+
## Development
141+
142+
### Project Structure
143+
144+
```
145+
src/kagent_slackbot/
146+
├── main.py # Entry point, AsyncApp initialization
147+
├── config.py # Configuration management
148+
├── constants.py # Application constants
149+
├── handlers/ # Slack event handlers
150+
│ ├── mentions.py # @mention handling
151+
│ ├── commands.py # Slash command handling
152+
│ └── middleware.py # Prometheus metrics
153+
├── services/ # Business logic
154+
│ ├── a2a_client.py # Kagent A2A protocol client
155+
│ ├── agent_discovery.py # Agent discovery from API
156+
│ └── agent_router.py # Agent routing logic
157+
└── slack/ # Slack utilities
158+
├── formatters.py # Block Kit formatting
159+
└── validators.py # Input validation
160+
```
161+
162+
### Type Checking
163+
164+
```bash
165+
.venv/bin/mypy src/kagent_slackbot/
166+
```
167+
168+
### Linting
169+
170+
```bash
171+
.venv/bin/ruff check src/
172+
```
173+
174+
Auto-fix issues:
175+
```bash
176+
.venv/bin/ruff check --fix src/
177+
```
178+
179+
## Deployment
180+
181+
### Kubernetes
182+
183+
1. Ensure the `kagent` namespace exists (created by kagent helm chart)
184+
185+
2. Create secrets (update with your tokens):
186+
```bash
187+
kubectl create secret generic slackbot-secrets \
188+
--namespace=kagent \
189+
--from-literal=slack-bot-token=xoxb-... \
190+
--from-literal=slack-app-token=xapp-... \
191+
--from-literal=slack-signing-secret=...
192+
```
193+
194+
3. Apply manifests:
195+
```bash
196+
kubectl apply -f slackbot/manifests/k8s/
197+
```
198+
199+
4. Verify deployment:
200+
```bash
201+
kubectl get pods -n kagent -l app=slackbot
202+
kubectl logs -f -n kagent deployment/slackbot
203+
```
204+
205+
### Monitoring
206+
207+
**Prometheus Metrics** available at `/metrics`:
208+
- `slack_messages_total{event_type, status}` - Total messages processed
209+
- `slack_message_duration_seconds{event_type}` - Message processing time
210+
- `slack_commands_total{command, status}` - Slash command counts
211+
- `agent_invocations_total{agent, status}` - Agent invocation counts
212+
213+
**Health Endpoints**:
214+
- `/health` - Liveness probe
215+
- `/ready` - Readiness probe
216+
217+
**Structured Logs**: JSON format with fields:
218+
- `event`: Log message
219+
- `level`: Log level (INFO, ERROR, etc.)
220+
- `timestamp`: ISO 8601 timestamp
221+
- `user`, `agent`, `session`: Contextual fields
222+
223+
## Troubleshooting
224+
225+
### Bot doesn't respond to @mentions
226+
227+
1. Check bot is online: `kubectl logs -n kagent deployment/slackbot`
228+
2. Verify Socket Mode connection is established (look for "Connecting to Slack via Socket Mode")
229+
3. Ensure Slack app has `app_mentions:read` scope
230+
4. Check event subscription for `app_mention` is configured
231+
232+
### Agent discovery fails
233+
234+
1. Verify Kagent is accessible: `curl http://kagent-controller.kagent.svc.cluster.local:8083/api/agents`
235+
2. Check logs for "Agent discovery failed" messages
236+
3. Ensure `KAGENT_BASE_URL` is configured correctly
237+
238+
### Type errors during development
239+
240+
Run type checking:
241+
```bash
242+
.venv/bin/mypy src/kagent_slackbot/
243+
```
244+
245+
Common issues:
246+
- Missing type annotations - add explicit types
247+
- Untyped external libraries - use `# type: ignore[no-untyped-call]`
248+
249+
## References
250+
251+
- **Slack Bolt Docs**: https://slack.dev/bolt-python/
252+
- **Kagent A2A Protocol**: `go/internal/a2a/`
253+
- **Agent CRD Spec**: `go/api/v1alpha2/agent_types.go`
254+
255+
## License
256+
257+
See LICENSE file for details.

0 commit comments

Comments
 (0)