Skip to content

Commit cd76e9f

Browse files
committed
feat: add Slack bot integration for kagent
- Socket Mode bot for DMs and @mentions - Agent discovery and routing - Streaming responses with human-in-the-loop approval - RBAC with Slack user groups - Prometheus metrics and structured logging - Production-ready Dockerfile with Python 3.13
1 parent b1f142a commit cd76e9f

39 files changed

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

0 commit comments

Comments
 (0)