@uniquedivine/mcp-slack 0.0.0-stage → 4.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,945 @@
1
+ /**
2
+ * Tool Handlers
3
+ *
4
+ * Implementation of all MCP tool handlers.
5
+ */
6
+
7
+ import { writeFileSync, readFileSync, existsSync, renameSync, unlinkSync, mkdirSync, chmodSync } from "fs";
8
+ import { homedir, platform } from "os";
9
+ import { join } from "path";
10
+ import {
11
+ loadTokensReadOnly,
12
+ saveTokens,
13
+ extractFromChrome,
14
+ isAutoRefreshAvailable,
15
+ getLastExtractionError
16
+ } from "./token-store.js";
17
+ import { slackAPI, resolveUser, formatTimestamp, sleep, checkTokenHealth, getUserCacheStats } from "./slack-client.js";
18
+ import {
19
+ saveProfile as workflowSaveProfile,
20
+ listProfiles as workflowListProfiles,
21
+ ALLOWED_WORKFLOW_KINDS_LIST,
22
+ } from "./workflow-store.js";
23
+ import { withRichMessageFields } from "./rich-message-fields.js";
24
+ import { isAuthDeath, lifeboatResponse } from "./lifeboat.js";
25
+
26
+ // ============ Utilities ============
27
+
28
+ /**
29
+ * Robust boolean parser for LLM input unpredictability
30
+ * Handles: true, "true", "True", "1", 1, "yes", etc.
31
+ */
32
+ function parseBool(val) {
33
+ if (typeof val === 'boolean') return val;
34
+ if (typeof val === 'number') return val !== 0;
35
+ if (typeof val === 'string') {
36
+ return ['true', '1', 'yes', 'on'].includes(val.toLowerCase());
37
+ }
38
+ return false;
39
+ }
40
+
41
+ function asMcpJson(payload, isError = false) {
42
+ return {
43
+ content: [{
44
+ type: "text",
45
+ text: JSON.stringify(payload, null, 2)
46
+ }],
47
+ ...(isError ? { isError: true } : {})
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Atomic write to prevent file corruption from concurrent writes
53
+ */
54
+ function atomicWriteSync(filePath, content) {
55
+ const tempPath = `${filePath}.${process.pid}.tmp`;
56
+ try {
57
+ writeFileSync(tempPath, content);
58
+ if (platform() === 'darwin' || platform() === 'linux') {
59
+ try { chmodSync(tempPath, 0o600); } catch {}
60
+ }
61
+ renameSync(tempPath, filePath);
62
+ } catch (e) {
63
+ try { unlinkSync(tempPath); } catch {}
64
+ throw e;
65
+ }
66
+ }
67
+
68
+ // ============ DM Cache ============
69
+ const DM_CACHE_FILE = join(homedir(), ".slack-mcp-dm-cache.json");
70
+ const DM_CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours
71
+
72
+ function loadDMCache() {
73
+ if (!existsSync(DM_CACHE_FILE)) return { dms: {}, updated: 0 };
74
+ try {
75
+ const data = JSON.parse(readFileSync(DM_CACHE_FILE, "utf-8"));
76
+ // Check if cache is stale
77
+ if (Date.now() - (data.updated || 0) > DM_CACHE_TTL) {
78
+ return { dms: {}, updated: 0 };
79
+ }
80
+ return data;
81
+ } catch {
82
+ return { dms: {}, updated: 0 };
83
+ }
84
+ }
85
+
86
+ function saveDMCache(dms) {
87
+ try {
88
+ const data = { dms, updated: Date.now() };
89
+ atomicWriteSync(DM_CACHE_FILE, JSON.stringify(data, null, 2));
90
+ } catch {
91
+ // Ignore write errors - cache is optional
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Token status handler - detailed token health info
97
+ */
98
+ export async function handleTokenStatus() {
99
+ const health = await checkTokenHealth({ error: () => {} });
100
+ const cacheStats = getUserCacheStats();
101
+ const dmCache = loadDMCache();
102
+ const tokenStatus = health.reason === 'no_tokens'
103
+ ? "missing"
104
+ : health.age_state === "unknown"
105
+ ? "unknown_age"
106
+ : health.critical
107
+ ? "critical"
108
+ : health.warning
109
+ ? "warning"
110
+ : "healthy";
111
+
112
+ return asMcpJson({
113
+ status: tokenStatus,
114
+ code: health.reason
115
+ || (health.age_state === "unknown" ? "unknown_age" : null)
116
+ || (health.critical ? "token_critical" : health.warning ? "token_warning" : "ok"),
117
+ message: health.message,
118
+ next_action: health.reason === 'no_tokens' ? "Run bunx @uniquedivine/mcp-slack --setup" : null,
119
+ details: {
120
+ age_known: health.age_known,
121
+ age_state: health.age_state
122
+ },
123
+ token: {
124
+ status: tokenStatus,
125
+ age_hours: health.age_hours,
126
+ source: health.source,
127
+ updated_at: health.updated_at
128
+ },
129
+ auto_refresh: {
130
+ enabled: isAutoRefreshAvailable(),
131
+ interval: "4 hours",
132
+ last_attempt: health.refreshed ? "just_now" : null,
133
+ requires: isAutoRefreshAvailable() ? "Slack tab open in Chrome" : "Not supported on this platform"
134
+ },
135
+ cache: {
136
+ users: cacheStats,
137
+ dms: {
138
+ count: Object.keys(dmCache.dms || {}).length,
139
+ age_hours: dmCache.updated ? Math.round((Date.now() - dmCache.updated) / (60 * 60 * 1000) * 10) / 10 : null
140
+ }
141
+ }
142
+ });
143
+ }
144
+
145
+ /**
146
+ * Health check handler
147
+ */
148
+ export async function handleHealthCheck() {
149
+ const creds = loadTokensReadOnly();
150
+ if (!creds) {
151
+ return asMcpJson({
152
+ status: "error",
153
+ code: "missing_credentials",
154
+ message: "No credentials found",
155
+ next_action: "Run bunx @uniquedivine/mcp-slack --setup"
156
+ }, true);
157
+ }
158
+
159
+ try {
160
+ const result = await slackAPI("auth.test", {}, { retryOnAuthFail: false });
161
+ return asMcpJson({
162
+ status: "ok",
163
+ code: "ok",
164
+ message: "Slack auth valid",
165
+ user: result.user,
166
+ user_id: result.user_id,
167
+ team: result.team,
168
+ team_id: result.team_id,
169
+ token_source: creds.source,
170
+ token_updated: creds.updatedAt || null
171
+ });
172
+ } catch (e) {
173
+ // OAuth Lifeboat: a dead session token here is the most common first
174
+ // signal of token death — hand back recovery guidance, not a bare error.
175
+ // lifeboatResponse keeps the shape identical across all three call sites.
176
+ if (isAuthDeath(e)) {
177
+ return lifeboatResponse(e);
178
+ }
179
+ return asMcpJson({
180
+ status: "error",
181
+ code: "auth_failed",
182
+ message: e.message,
183
+ next_action: "Run bunx @uniquedivine/mcp-slack --setup"
184
+ }, true);
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Refresh tokens handler
190
+ */
191
+ export async function handleRefreshTokens() {
192
+ // Check platform support
193
+ if (!isAutoRefreshAvailable()) {
194
+ return asMcpJson({
195
+ status: "error",
196
+ code: "unsupported_platform",
197
+ message: "Auto-refresh is only available on macOS.",
198
+ next_action: "Manually update ~/.slack-mcp-tokens.json with SLACK_TOKEN and SLACK_COOKIE."
199
+ }, true);
200
+ }
201
+
202
+ const chromeTokens = extractFromChrome();
203
+ if (chromeTokens) {
204
+ saveTokens(chromeTokens.token, chromeTokens.cookie);
205
+ try {
206
+ const result = await slackAPI("auth.test", {}, { retryOnAuthFail: false });
207
+ return asMcpJson({
208
+ status: "ok",
209
+ code: "refreshed",
210
+ message: "Tokens refreshed from Chrome.",
211
+ user: result.user,
212
+ team: result.team
213
+ });
214
+ } catch (e) {
215
+ return asMcpJson({
216
+ status: "error",
217
+ code: "auth_failed_after_refresh",
218
+ message: e.message,
219
+ next_action: "Refresh Slack in Chrome and rerun slack_refresh_tokens."
220
+ }, true);
221
+ }
222
+ }
223
+
224
+ const extractionError = getLastExtractionError();
225
+ if (extractionError?.code === "apple_events_javascript_disabled") {
226
+ return asMcpJson({
227
+ status: "error",
228
+ code: extractionError.code,
229
+ message: extractionError.message,
230
+ detail: extractionError.detail,
231
+ next_action: "In Chrome: View > Developer > Allow JavaScript from Apple Events, then retry. (Only needed for token — cookie is extracted from Chrome's database automatically.)"
232
+ }, true);
233
+ }
234
+
235
+ return asMcpJson({
236
+ status: "error",
237
+ code: extractionError?.code || "chrome_extraction_failed",
238
+ message: extractionError?.message || "Could not extract tokens from Chrome.",
239
+ detail: extractionError?.detail || "Ensure Chrome is running with a logged-in Slack tab at app.slack.com.",
240
+ next_action: "Open Slack in Chrome and run slack_refresh_tokens again."
241
+ }, true);
242
+ }
243
+
244
+ /**
245
+ * List conversations handler (with lazy DM discovery)
246
+ */
247
+ export async function handleListConversations(args) {
248
+ const types = args.types || "im,mpim";
249
+ const wantsDMs = types.includes("im") || types.includes("mpim");
250
+ const discoverDMs = parseBool(args.discover_dms); // Robust boolean parsing
251
+
252
+ const result = await slackAPI("conversations.list", {
253
+ types: types,
254
+ limit: args.limit || 100,
255
+ exclude_archived: true
256
+ });
257
+
258
+ const conversations = await Promise.all((result.channels || []).map(async (c) => {
259
+ let displayName = c.name;
260
+ if (c.is_im && c.user) {
261
+ displayName = await resolveUser(c.user);
262
+ }
263
+ return {
264
+ id: c.id,
265
+ name: displayName,
266
+ type: c.is_im ? "dm" : c.is_mpim ? "group_dm" : c.is_private ? "private_channel" : "public_channel",
267
+ user_id: c.user
268
+ };
269
+ }));
270
+
271
+ // Load cached DMs first (fast path)
272
+ const dmCache = loadDMCache();
273
+ for (const [channelId, data] of Object.entries(dmCache.dms || {})) {
274
+ if (!conversations.find(c => c.id === channelId)) {
275
+ conversations.push(data);
276
+ }
277
+ }
278
+
279
+ // Only do expensive full DM discovery if explicitly requested
280
+ // This avoids hitting rate limits on large workspaces
281
+ if (wantsDMs && discoverDMs) {
282
+ const newDMs = { ...dmCache.dms };
283
+ let discoveredCount = 0;
284
+
285
+ try {
286
+ const usersResult = await slackAPI("users.list", { limit: 200 });
287
+ for (const user of (usersResult.members || [])) {
288
+ if (user.is_bot || user.id === "USLACKBOT" || user.deleted) continue;
289
+
290
+ // Skip if we already have this user's DM
291
+ const existingDM = conversations.find(c => c.user_id === user.id && c.type === "dm");
292
+ if (existingDM) continue;
293
+
294
+ // Try to open DM with this user
295
+ try {
296
+ const dmResult = await slackAPI("conversations.open", { users: user.id });
297
+ if (dmResult.channel?.id) {
298
+ const channelId = dmResult.channel.id;
299
+ if (!conversations.find(c => c.id === channelId)) {
300
+ const dmData = {
301
+ id: channelId,
302
+ name: user.real_name || user.name,
303
+ type: "dm",
304
+ user_id: user.id
305
+ };
306
+ conversations.push(dmData);
307
+ newDMs[channelId] = dmData;
308
+ discoveredCount++;
309
+ }
310
+ }
311
+ // Rate limit protection
312
+ await sleep(50);
313
+ } catch (e) {
314
+ // Skip users we can't DM
315
+ }
316
+ }
317
+ } catch (e) {
318
+ // If users.list fails, continue with what we have
319
+ }
320
+
321
+ // Save updated cache
322
+ if (discoveredCount > 0) {
323
+ saveDMCache(newDMs);
324
+ }
325
+ }
326
+
327
+ return {
328
+ content: [{
329
+ type: "text",
330
+ text: JSON.stringify({
331
+ count: conversations.length,
332
+ conversations,
333
+ cached_dms: Object.keys(dmCache.dms || {}).length,
334
+ hint: !discoverDMs && wantsDMs ? "Use discover_dms:true for full DM discovery (slower)" : undefined
335
+ }, null, 2)
336
+ }]
337
+ };
338
+ }
339
+
340
+ /**
341
+ * Conversations history handler
342
+ */
343
+ export async function handleConversationsHistory(args) {
344
+ const resolveUsers = args.resolve_users !== false;
345
+ const includeRichMessageFields = parseBool(args.include_rich_message_fields);
346
+ const historyParams = {
347
+ channel: args.channel_id,
348
+ limit: args.limit || 50,
349
+ oldest: args.oldest,
350
+ latest: args.latest,
351
+ include_all_metadata: parseBool(args.include_all_metadata)
352
+ };
353
+ // Only opt into boundary-inclusive reads when a boundary was actually
354
+ // provided — otherwise leave Slack's default behavior untouched.
355
+ if (args.oldest || args.latest) historyParams.inclusive = true;
356
+ const result = await slackAPI("conversations.history", historyParams);
357
+
358
+ const messages = await Promise.all((result.messages || []).map(async (msg) => {
359
+ const userName = resolveUsers ? await resolveUser(msg.user) : msg.user;
360
+ return withRichMessageFields({
361
+ ts: msg.ts,
362
+ user: userName,
363
+ user_id: msg.user,
364
+ text: msg.text || "",
365
+ datetime: formatTimestamp(msg.ts),
366
+ has_thread: !!msg.thread_ts && msg.reply_count > 0,
367
+ reply_count: msg.reply_count
368
+ }, msg, includeRichMessageFields);
369
+ }));
370
+
371
+ return {
372
+ content: [{
373
+ type: "text",
374
+ text: JSON.stringify({
375
+ channel: args.channel_id,
376
+ message_count: messages.length,
377
+ has_more: result.has_more,
378
+ messages
379
+ }, null, 2)
380
+ }]
381
+ };
382
+ }
383
+
384
+ /**
385
+ * Full conversation export handler
386
+ */
387
+ export async function handleGetFullConversation(args) {
388
+ const maxMessages = Math.min(args.max_messages || 2000, 10000);
389
+ const includeThreads = args.include_threads !== false;
390
+ const includeRichMessageFields = parseBool(args.include_rich_message_fields);
391
+ const allMessages = [];
392
+ let cursor;
393
+ let hasMore = true;
394
+
395
+ // Fetch all messages with pagination
396
+ while (hasMore && allMessages.length < maxMessages) {
397
+ const historyParams = {
398
+ channel: args.channel_id,
399
+ limit: Math.min(100, maxMessages - allMessages.length),
400
+ oldest: args.oldest,
401
+ latest: args.latest,
402
+ cursor,
403
+ include_all_metadata: parseBool(args.include_all_metadata)
404
+ };
405
+ // Boundary-inclusive only when a boundary was actually provided —
406
+ // otherwise leave Slack's default behavior untouched.
407
+ if (args.oldest || args.latest) historyParams.inclusive = true;
408
+ const result = await slackAPI("conversations.history", historyParams);
409
+
410
+ for (const msg of result.messages || []) {
411
+ const userName = await resolveUser(msg.user);
412
+ const message = withRichMessageFields({
413
+ ts: msg.ts,
414
+ user: userName,
415
+ user_id: msg.user,
416
+ text: msg.text || "",
417
+ datetime: formatTimestamp(msg.ts),
418
+ replies: []
419
+ }, msg, includeRichMessageFields);
420
+
421
+ // Fetch thread replies if present
422
+ if (includeThreads && msg.reply_count > 0) {
423
+ try {
424
+ const threadResult = await slackAPI("conversations.replies", {
425
+ channel: args.channel_id,
426
+ ts: msg.ts,
427
+ include_all_metadata: parseBool(args.include_all_metadata)
428
+ });
429
+ // Skip first message (parent)
430
+ for (const reply of (threadResult.messages || []).slice(1)) {
431
+ const replyUserName = await resolveUser(reply.user);
432
+ message.replies.push(withRichMessageFields({
433
+ ts: reply.ts,
434
+ user: replyUserName,
435
+ text: reply.text || "",
436
+ datetime: formatTimestamp(reply.ts)
437
+ }, reply, includeRichMessageFields));
438
+ }
439
+ await sleep(50); // Rate limit
440
+ } catch (e) {
441
+ // Skip thread on error
442
+ }
443
+ }
444
+
445
+ allMessages.push(message);
446
+ }
447
+
448
+ hasMore = result.has_more && result.response_metadata?.next_cursor;
449
+ cursor = result.response_metadata?.next_cursor;
450
+ if (hasMore) await sleep(100);
451
+ }
452
+
453
+ // Sort chronologically
454
+ allMessages.sort((a, b) => parseFloat(a.ts) - parseFloat(b.ts));
455
+
456
+ const output = {
457
+ channel: args.channel_id,
458
+ exported_at: new Date().toISOString(),
459
+ total_messages: allMessages.length,
460
+ date_range: {
461
+ oldest: args.oldest ? formatTimestamp(args.oldest) : "beginning",
462
+ latest: args.latest ? formatTimestamp(args.latest) : "now"
463
+ },
464
+ messages: allMessages
465
+ };
466
+
467
+ // Save to file if requested (restricted to ~/.slack-mcp-exports/ for security)
468
+ if (args.output_file) {
469
+ const exportDir = join(homedir(), '.slack-mcp-exports');
470
+ // Ensure export directory exists
471
+ try { mkdirSync(exportDir, { recursive: true }); } catch {}
472
+
473
+ // Sanitize filename - remove any path traversal attempts
474
+ const sanitizedName = args.output_file
475
+ .replace(/^.*[\\\/]/, '') // Remove any path components
476
+ .replace(/\.\./g, '') // Remove .. sequences
477
+ .replace(/[<>:"|?*]/g, '') // Remove invalid chars
478
+ || 'export.json';
479
+
480
+ const outputPath = join(exportDir, sanitizedName);
481
+ writeFileSync(outputPath, JSON.stringify(output, null, 2));
482
+ output.saved_to = outputPath;
483
+ }
484
+
485
+ return { content: [{ type: "text", text: JSON.stringify(output, null, 2) }] };
486
+ }
487
+
488
+ /**
489
+ * Search messages handler
490
+ */
491
+ export async function handleSearchMessages(args) {
492
+ const includeRichMessageFields = parseBool(args.include_rich_message_fields);
493
+ const result = await slackAPI("search.messages", {
494
+ query: args.query,
495
+ count: args.count || 20,
496
+ sort: "timestamp",
497
+ sort_dir: "desc"
498
+ });
499
+
500
+ const matches = await Promise.all((result.messages?.matches || []).map(async (m) => withRichMessageFields({
501
+ ts: m.ts,
502
+ channel: m.channel?.name || m.channel?.id,
503
+ channel_id: m.channel?.id,
504
+ user: await resolveUser(m.user),
505
+ text: m.text,
506
+ datetime: formatTimestamp(m.ts),
507
+ permalink: m.permalink
508
+ }, m, includeRichMessageFields)));
509
+
510
+ return {
511
+ content: [{
512
+ type: "text",
513
+ text: JSON.stringify({
514
+ query: args.query,
515
+ total: result.messages?.total || 0,
516
+ matches
517
+ }, null, 2)
518
+ }]
519
+ };
520
+ }
521
+
522
+ /**
523
+ * User info handler
524
+ */
525
+ export async function handleUsersInfo(args) {
526
+ const result = await slackAPI("users.info", { user: args.user_id });
527
+ const user = result.user;
528
+ return {
529
+ content: [{
530
+ type: "text",
531
+ text: JSON.stringify({
532
+ id: user.id,
533
+ name: user.name,
534
+ real_name: user.real_name,
535
+ display_name: user.profile?.display_name,
536
+ email: user.profile?.email,
537
+ title: user.profile?.title,
538
+ status_text: user.profile?.status_text,
539
+ status_emoji: user.profile?.status_emoji,
540
+ timezone: user.tz,
541
+ is_bot: user.is_bot,
542
+ is_admin: user.is_admin
543
+ }, null, 2)
544
+ }]
545
+ };
546
+ }
547
+
548
+ /**
549
+ * Send message handler
550
+ */
551
+ export async function handleSendMessage(args) {
552
+ const result = await slackAPI("chat.postMessage", {
553
+ channel: args.channel_id,
554
+ text: args.text,
555
+ thread_ts: args.thread_ts
556
+ });
557
+
558
+ return {
559
+ content: [{
560
+ type: "text",
561
+ text: JSON.stringify({
562
+ status: "sent",
563
+ channel: result.channel,
564
+ ts: result.ts,
565
+ thread_ts: args.thread_ts,
566
+ message: result.message?.text
567
+ }, null, 2)
568
+ }]
569
+ };
570
+ }
571
+
572
+ /**
573
+ * Get thread handler
574
+ */
575
+ export async function handleGetThread(args) {
576
+ const includeRichMessageFields = parseBool(args.include_rich_message_fields);
577
+ const result = await slackAPI("conversations.replies", {
578
+ channel: args.channel_id,
579
+ ts: args.thread_ts,
580
+ include_all_metadata: parseBool(args.include_all_metadata)
581
+ });
582
+
583
+ const messages = await Promise.all((result.messages || []).map(async (msg) => withRichMessageFields({
584
+ ts: msg.ts,
585
+ user: await resolveUser(msg.user),
586
+ user_id: msg.user,
587
+ text: msg.text || "",
588
+ datetime: formatTimestamp(msg.ts),
589
+ is_parent: msg.ts === args.thread_ts
590
+ }, msg, includeRichMessageFields)));
591
+
592
+ return {
593
+ content: [{
594
+ type: "text",
595
+ text: JSON.stringify({
596
+ channel: args.channel_id,
597
+ thread_ts: args.thread_ts,
598
+ message_count: messages.length,
599
+ messages
600
+ }, null, 2)
601
+ }]
602
+ };
603
+ }
604
+
605
+ /**
606
+ * List users handler (with pagination support)
607
+ */
608
+ export async function handleListUsers(args) {
609
+ const maxUsers = args.limit || 500;
610
+ const allUsers = [];
611
+ let cursor;
612
+
613
+ do {
614
+ const result = await slackAPI("users.list", {
615
+ limit: Math.min(200, maxUsers - allUsers.length),
616
+ cursor
617
+ });
618
+
619
+ const users = (result.members || [])
620
+ .filter(u => !u.deleted && !u.is_bot)
621
+ .map(u => ({
622
+ id: u.id,
623
+ name: u.name,
624
+ real_name: u.real_name,
625
+ display_name: u.profile?.display_name,
626
+ email: u.profile?.email,
627
+ is_admin: u.is_admin
628
+ }));
629
+
630
+ allUsers.push(...users);
631
+ cursor = result.response_metadata?.next_cursor;
632
+
633
+ // Small delay between pagination requests
634
+ if (cursor && allUsers.length < maxUsers) {
635
+ await sleep(100);
636
+ }
637
+ } while (cursor && allUsers.length < maxUsers);
638
+
639
+ return {
640
+ content: [{
641
+ type: "text",
642
+ text: JSON.stringify({ count: allUsers.length, users: allUsers }, null, 2)
643
+ }]
644
+ };
645
+ }
646
+
647
+ /**
648
+ * Add reaction handler
649
+ */
650
+ export async function handleAddReaction(args) {
651
+ await slackAPI("reactions.add", {
652
+ channel: args.channel_id,
653
+ timestamp: args.timestamp,
654
+ name: args.reaction
655
+ });
656
+
657
+ return {
658
+ content: [{
659
+ type: "text",
660
+ text: JSON.stringify({
661
+ status: "added",
662
+ channel: args.channel_id,
663
+ timestamp: args.timestamp,
664
+ reaction: args.reaction
665
+ }, null, 2)
666
+ }]
667
+ };
668
+ }
669
+
670
+ /**
671
+ * Remove reaction handler
672
+ */
673
+ export async function handleRemoveReaction(args) {
674
+ await slackAPI("reactions.remove", {
675
+ channel: args.channel_id,
676
+ timestamp: args.timestamp,
677
+ name: args.reaction
678
+ });
679
+
680
+ return {
681
+ content: [{
682
+ type: "text",
683
+ text: JSON.stringify({
684
+ status: "removed",
685
+ channel: args.channel_id,
686
+ timestamp: args.timestamp,
687
+ reaction: args.reaction
688
+ }, null, 2)
689
+ }]
690
+ };
691
+ }
692
+
693
+ /**
694
+ * Mark conversation as read handler
695
+ */
696
+ export async function handleConversationsMark(args) {
697
+ await slackAPI("conversations.mark", {
698
+ channel: args.channel_id,
699
+ ts: args.timestamp
700
+ });
701
+
702
+ return asMcpJson({
703
+ status: "marked",
704
+ channel: args.channel_id,
705
+ read_up_to: args.timestamp
706
+ });
707
+ }
708
+
709
+ /**
710
+ * Unread conversations handler - returns channels/DMs with unread messages
711
+ */
712
+ export async function handleConversationsUnreads(args) {
713
+ const types = args.types || "im,mpim,public_channel,private_channel";
714
+ const limit = args.limit || 50;
715
+
716
+ const result = await slackAPI("conversations.list", {
717
+ types,
718
+ limit: 200,
719
+ exclude_archived: true
720
+ });
721
+
722
+ // Filter to conversations with unreads and resolve names
723
+ const unreads = [];
724
+ for (const c of (result.channels || [])) {
725
+ const unreadCount = c.unread_count_display || c.unread_count || 0;
726
+ if (unreadCount === 0) continue;
727
+
728
+ let displayName = c.name;
729
+ if (c.is_im && c.user) {
730
+ displayName = await resolveUser(c.user);
731
+ }
732
+
733
+ unreads.push({
734
+ id: c.id,
735
+ name: displayName,
736
+ type: c.is_im ? "dm" : c.is_mpim ? "group_dm" : c.is_private ? "private_channel" : "public_channel",
737
+ unread_count: unreadCount,
738
+ latest_ts: c.latest?.ts || null
739
+ });
740
+ }
741
+
742
+ // Sort by unread count descending
743
+ unreads.sort((a, b) => b.unread_count - a.unread_count);
744
+
745
+ return asMcpJson({
746
+ total_unread_conversations: unreads.length,
747
+ conversations: unreads.slice(0, limit)
748
+ });
749
+ }
750
+
751
+ /**
752
+ * Search users handler - client-side filter on users.list
753
+ */
754
+ // Explicit scan cap for client-side user search: stop paginating after
755
+ // scanning this many workspace users (or when the cursor is exhausted) and
756
+ // flag the result as truncated so total_matches is never misreported as
757
+ // complete.
758
+ const USERS_SEARCH_MAX_SCANNED = 1000;
759
+
760
+ export async function handleUsersSearch(args) {
761
+ const rawQuery = typeof args.query === "string" ? args.query : "";
762
+ const query = rawQuery.trim().toLowerCase();
763
+ const limit = args.limit || 20;
764
+
765
+ // An empty/whitespace query would match every user in the workspace.
766
+ if (!query) {
767
+ return asMcpJson({
768
+ status: "error",
769
+ code: "invalid_arguments",
770
+ message: "query must be a non-empty string (an empty query would match all users).",
771
+ next_action: "Provide a name, display name, real name, or email fragment to search for."
772
+ }, true);
773
+ }
774
+
775
+ // Fetch users (paginated) and filter client-side
776
+ const allUsers = [];
777
+ let cursor;
778
+ let scannedUsers = 0;
779
+ let truncated = false;
780
+
781
+ do {
782
+ const result = await slackAPI("users.list", {
783
+ limit: 200,
784
+ cursor
785
+ });
786
+
787
+ for (const u of (result.members || [])) {
788
+ scannedUsers++;
789
+ if (u.deleted || u.is_bot || u.id === "USLACKBOT") continue;
790
+
791
+ const searchFields = [
792
+ u.name,
793
+ u.real_name,
794
+ u.profile?.display_name,
795
+ u.profile?.email
796
+ ].filter(Boolean).map(s => s.toLowerCase());
797
+
798
+ if (searchFields.some(f => f.includes(query))) {
799
+ allUsers.push({
800
+ id: u.id,
801
+ name: u.name,
802
+ real_name: u.real_name,
803
+ display_name: u.profile?.display_name,
804
+ email: u.profile?.email,
805
+ title: u.profile?.title,
806
+ is_admin: u.is_admin
807
+ });
808
+ }
809
+ }
810
+
811
+ cursor = result.response_metadata?.next_cursor;
812
+ if (cursor && scannedUsers >= USERS_SEARCH_MAX_SCANNED) {
813
+ truncated = true;
814
+ break;
815
+ }
816
+ if (cursor) await sleep(100);
817
+ } while (cursor);
818
+
819
+ return asMcpJson({
820
+ query: args.query,
821
+ count: Math.min(allUsers.length, limit),
822
+ total_matches: allUsers.length,
823
+ truncated,
824
+ users: allUsers.slice(0, limit)
825
+ });
826
+ }
827
+
828
+ // ============ Workflow Profile Primitives (OSS) ============
829
+
830
+ /**
831
+ * Save (or update) a workflow profile to ~/.slack-mcp-workflows.json
832
+ * Profile binds a workflow_kind to channels + priority_people + retention + cadence.
833
+ */
834
+ export async function handleWorkflowSave(args) {
835
+ const safeArgs = args || {};
836
+ const result = workflowSaveProfile({
837
+ profile_name: safeArgs.profile_name,
838
+ workflow_kind: safeArgs.workflow_kind,
839
+ channels: safeArgs.channels,
840
+ priority_people: safeArgs.priority_people,
841
+ retention_mode: safeArgs.retention_mode,
842
+ summary_cadence: safeArgs.summary_cadence,
843
+ });
844
+ if (!result.ok) {
845
+ return asMcpJson({ error: "invalid_workflow_profile", errors: result.errors }, true);
846
+ }
847
+ return asMcpJson({
848
+ ok: true,
849
+ profile_name: result.profile_name,
850
+ profile: result.profile,
851
+ note: "Profile saved locally. Hosted free tier syncs profiles automatically when you connect your account; OSS-only mode keeps them on your machine.",
852
+ });
853
+ }
854
+
855
+ /**
856
+ * List saved workflow profiles, optionally filtered by workflow_kind.
857
+ */
858
+ export async function handleWorkflows(args) {
859
+ const result = workflowListProfiles({ workflow_kind: args && args.workflow_kind });
860
+ if (!result.ok) {
861
+ return asMcpJson({ error: "invalid_workflow_filter", errors: result.errors }, true);
862
+ }
863
+ return asMcpJson({
864
+ ok: true,
865
+ count: result.profiles.length,
866
+ workflow_kinds: ALLOWED_WORKFLOW_KINDS_LIST,
867
+ profiles: result.profiles,
868
+ });
869
+ }
870
+
871
+ // ============ Hosted-Only AI Tool Stubs ============
872
+ // These three tools appear in the OSS package's MCP tool list so users
873
+ // discover them. The handlers return a structured upgrade message —
874
+ // actual execution happens on the hosted worker (mcp.revasserlabs.com).
875
+
876
+ const HOSTED_UPGRADE_PAYLOAD = {
877
+ error: "tool_requires_hosted",
878
+ message: "This tool needs hosted mode (Vectorize + Workers AI). Get free monthly credits at mcp.revasserlabs.com — no card required.",
879
+ signup_url: "https://mcp.revasserlabs.com/signup",
880
+ upgrade_url: "https://mcp.revasserlabs.com/pricing",
881
+ free_tier_quota: "2,000 requests/mo + 25 AI tool calls/mo (no card)",
882
+ pro_value_prop: "Pro $19/mo unlocks unlimited requests and AI tool calls, permanent OAuth (no token rotation).",
883
+ };
884
+
885
+ export async function handleSmartSearch(args) {
886
+ return asMcpJson(
887
+ {
888
+ ...HOSTED_UPGRADE_PAYLOAD,
889
+ requested: { tool: "slack_smart_search", args: args || {} },
890
+ },
891
+ true
892
+ );
893
+ }
894
+
895
+ export async function handleCatchMeUp(args) {
896
+ return asMcpJson(
897
+ {
898
+ ...HOSTED_UPGRADE_PAYLOAD,
899
+ requested: { tool: "slack_catch_me_up", args: args || {} },
900
+ },
901
+ true
902
+ );
903
+ }
904
+
905
+ export async function handleTriage(args) {
906
+ return asMcpJson(
907
+ {
908
+ ...HOSTED_UPGRADE_PAYLOAD,
909
+ requested: { tool: "slack_triage", args: args || {} },
910
+ },
911
+ true
912
+ );
913
+ }
914
+
915
+ // ============ Shared Tool Dispatch Map ============
916
+ // Single source of truth mapping every advertised tool name (lib/tools.js)
917
+ // to its handler. Both transports — stdio (src/server.js) and HTTP
918
+ // (src/server-http.js) — dispatch through this map so the advertised tool
919
+ // list and the dispatch surface cannot drift apart.
920
+
921
+ export const TOOL_HANDLERS = Object.freeze({
922
+ slack_token_status: handleTokenStatus,
923
+ slack_health_check: handleHealthCheck,
924
+ slack_refresh_tokens: handleRefreshTokens,
925
+ slack_list_conversations: handleListConversations,
926
+ slack_conversations_history: handleConversationsHistory,
927
+ slack_get_full_conversation: handleGetFullConversation,
928
+ slack_search_messages: handleSearchMessages,
929
+ slack_users_info: handleUsersInfo,
930
+ slack_send_message: handleSendMessage,
931
+ slack_get_thread: handleGetThread,
932
+ slack_list_users: handleListUsers,
933
+ slack_add_reaction: handleAddReaction,
934
+ slack_remove_reaction: handleRemoveReaction,
935
+ slack_conversations_mark: handleConversationsMark,
936
+ slack_conversations_unreads: handleConversationsUnreads,
937
+ slack_users_search: handleUsersSearch,
938
+ // Workflow profile primitives (OSS local JSON store)
939
+ slack_workflow_save: handleWorkflowSave,
940
+ slack_workflows: handleWorkflows,
941
+ // Hosted-only AI tools (OSS = upgrade stubs)
942
+ slack_smart_search: handleSmartSearch,
943
+ slack_catch_me_up: handleCatchMeUp,
944
+ slack_triage: handleTriage,
945
+ });