@uniquedivine/mcp-slack 4.5.1 → 4.5.2

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.
package/README.md CHANGED
@@ -11,8 +11,8 @@ in through a browser. Store credentials once, then run the published package
11
11
  with an exact version pin:
12
12
 
13
13
  ```sh
14
- bunx @uniquedivine/mcp-slack@4.5.1 --setup
15
- bunx @uniquedivine/mcp-slack@4.5.1
14
+ bunx @uniquedivine/mcp-slack@4.5.2 --setup
15
+ bunx @uniquedivine/mcp-slack@4.5.2
16
16
  ```
17
17
 
18
18
  Flag `--setup` writes file `~/.slack-mcp-tokens.json`. To pass environment
@@ -25,7 +25,7 @@ changes on `main`. The version pin selects the exact reviewed release that runs.
25
25
  ### Claude Code
26
26
 
27
27
  ```sh
28
- claude mcp add slack -- bunx @uniquedivine/mcp-slack@4.5.1
28
+ claude mcp add slack -- bunx @uniquedivine/mcp-slack@4.5.2
29
29
  ```
30
30
 
31
31
  ### Codex
@@ -35,7 +35,7 @@ Add this entry to file `~/.codex/config.toml`:
35
35
  ```toml
36
36
  [mcp_servers.slack]
37
37
  command = "bunx"
38
- args = ["@uniquedivine/mcp-slack@4.5.1"]
38
+ args = ["@uniquedivine/mcp-slack@4.5.2"]
39
39
  ```
40
40
 
41
41
  ### Cursor
@@ -48,7 +48,7 @@ a project:
48
48
  "mcpServers": {
49
49
  "slack": {
50
50
  "command": "bunx",
51
- "args": ["@uniquedivine/mcp-slack@4.5.1"]
51
+ "args": ["@uniquedivine/mcp-slack@4.5.2"]
52
52
  }
53
53
  }
54
54
  }
@@ -58,7 +58,7 @@ a project:
58
58
 
59
59
  1. Find the newest version with command
60
60
  `npm view @uniquedivine/mcp-slack version`.
61
- 2. Change the `@4.5.1` pin in the client configuration to that version.
61
+ 2. Change the `@4.5.2` pin in the client configuration to that version.
62
62
  3. Restart the MCP server in the client, or restart the client. In Claude
63
63
  Code, run `/mcp` and reconnect the server. Command `bunx` downloads the new
64
64
  version on the next launch.
package/docs/API.md CHANGED
@@ -319,6 +319,7 @@ Before it calls `chat.delete`, the tool checks the target:
319
319
  | `invalid_argument` | An argument is missing or malformed; `field` names it |
320
320
  | `message_too_old` | The message is older than the age window |
321
321
  | `message_not_found` | No message with that timestamp in the channel |
322
+ | `message_deleted` | Only a deleted thread parent's placeholder remains at that timestamp |
322
323
  | `lookup_incomplete` | The thread search hit its page cap before finding the message |
323
324
  | `not_own_message` | Someone else, or a bot, sent the message |
324
325
  | `text_mismatch` | `expected_text` doesn't match the message's text |
@@ -411,6 +412,7 @@ string of at most 4,000 characters.
411
412
  | `invalid_argument` | An argument is missing or malformed; `field` names it |
412
413
  | `message_too_old` | The message is older than the age window |
413
414
  | `message_not_found` | No message with that timestamp in the channel |
415
+ | `message_deleted` | Only a deleted thread parent's placeholder remains at that timestamp |
414
416
  | `lookup_incomplete` | The thread search hit its page cap before finding the message |
415
417
  | `not_own_message` | Someone else, or a bot, sent the message |
416
418
  | `text_mismatch` | `expected_text` doesn't match the message's text |
@@ -655,3 +657,32 @@ Search workspace users by name, display name, or email. Case-insensitive partial
655
657
  ]
656
658
  }
657
659
  ```
660
+
661
+ ## Write Log
662
+
663
+ Each call to `slack_delete_message`, `slack_delete_message_unsafe`,
664
+ `slack_update_message`, or `slack_update_message_unsafe` writes one line to
665
+ stderr, whether it succeeds, is refused, or throws:
666
+
667
+ ```text
668
+ slack-mcp write {"tool":"slack_delete_message","channel":"D063M4403MW","timestamp":"1767368030.607599","status":"deleted","code":null,"age_hours":0.2}
669
+ ```
670
+
671
+ | Field | Meaning |
672
+ |-------|---------|
673
+ | `tool` | The tool called |
674
+ | `channel` | `channel_id`, once Slack has answered `conversations.history` for it; otherwise `null` |
675
+ | `timestamp` | `timestamp`, once Slack has returned that message; otherwise `null` |
676
+ | `status` | `deleted`, `updated`, `probably_deleted`, `outcome_unknown`, `error`, or `thrown` |
677
+ | `code` | The error code, such as `text_mismatch`, or `null` on success |
678
+ | `age_hours` | The message's age in hours, once Slack has returned that message; otherwise `null` |
679
+
680
+ The line never includes tokens, cookies, or message text. `channel_id` and
681
+ `timestamp` come from the caller, and an ID shape proves nothing:
682
+ `C0NF1DENT1AL` looks like a channel ID. So the log writes the channel only
683
+ after Slack confirms the conversation exists, and the timestamp only after
684
+ Slack returns the message. A refusal before any Slack call, such as
685
+ `invalid_argument` or `message_too_old`, and a Slack error such as
686
+ `channel_not_found` or `not_in_channel` log both as `null`, along with
687
+ `age_hours`. A `message_too_old` result still reports the age to the caller. For
688
+ `message_not_found`, the channel is logged and the timestamp and age are `null`.
package/docs/SETUP.md CHANGED
@@ -17,9 +17,9 @@ A hosted version with permanent OAuth tokens, semantic search, and AI summaries
17
17
  ### 1. Install with Bun
18
18
 
19
19
  ```bash
20
- bun add -g @uniquedivine/mcp-slack@4.5.1
20
+ bun add -g @uniquedivine/mcp-slack@4.5.2
21
21
  # or run it without a global install:
22
- bunx @uniquedivine/mcp-slack@4.5.1 --version
22
+ bunx @uniquedivine/mcp-slack@4.5.2 --version
23
23
  ```
24
24
 
25
25
  ### 1b. Or Clone the Repository
@@ -35,9 +35,9 @@ bun install --frozen-lockfile
35
35
  ```bash
36
36
  tmpdir="$(mktemp -d)"
37
37
  cd "$tmpdir"
38
- bunx @uniquedivine/mcp-slack@4.5.1 --version
39
- bunx @uniquedivine/mcp-slack@4.5.1 --help
40
- bunx @uniquedivine/mcp-slack@4.5.1 --doctor
38
+ bunx @uniquedivine/mcp-slack@4.5.2 --version
39
+ bunx @uniquedivine/mcp-slack@4.5.2 --help
40
+ bunx @uniquedivine/mcp-slack@4.5.2 --doctor
41
41
  ```
42
42
 
43
43
  Expected:
@@ -57,7 +57,7 @@ Expected:
57
57
  2. Navigate to https://app.slack.com and log in
58
58
  3. Run:
59
59
  ```bash
60
- bunx @uniquedivine/mcp-slack@4.5.1 --setup
60
+ bunx @uniquedivine/mcp-slack@4.5.2 --setup
61
61
  ```
62
62
 
63
63
  **Option B: Automatic Extraction (repo clone workflow)**
@@ -93,7 +93,7 @@ npm run tokens:auto
93
93
  "mcpServers": {
94
94
  "slack": {
95
95
  "command": "bunx",
96
- "args": ["@uniquedivine/mcp-slack@4.5.1"]
96
+ "args": ["@uniquedivine/mcp-slack@4.5.2"]
97
97
  }
98
98
  }
99
99
  }
@@ -106,7 +106,7 @@ Fully restart Claude Desktop (Cmd+Q on macOS, then reopen).
106
106
  ### 5. Configure Claude Code (CLI)
107
107
 
108
108
  ```bash
109
- claude mcp add slack -- bunx @uniquedivine/mcp-slack@4.5.1
109
+ claude mcp add slack -- bunx @uniquedivine/mcp-slack@4.5.2
110
110
  ```
111
111
 
112
112
  Or manually edit `~/.claude.json`:
@@ -117,7 +117,7 @@ Or manually edit `~/.claude.json`:
117
117
  "slack": {
118
118
  "type": "stdio",
119
119
  "command": "bunx",
120
- "args": ["@uniquedivine/mcp-slack@4.5.1"]
120
+ "args": ["@uniquedivine/mcp-slack@4.5.2"]
121
121
  }
122
122
  }
123
123
  }
@@ -157,7 +157,7 @@ Create `~/Library/LaunchAgents/com.yourname.slack-token-refresh.plist`:
157
157
  <array>
158
158
  <string>/bin/bash</string>
159
159
  <string>-c</string>
160
- <string>exec "$HOME/.bun/bin/bunx" @uniquedivine/mcp-slack@4.5.1 --refresh-tokens</string>
160
+ <string>exec "$HOME/.bun/bin/bunx" @uniquedivine/mcp-slack@4.5.2 --refresh-tokens</string>
161
161
  </array>
162
162
  <key>StartCalendarInterval</key>
163
163
  <array>
@@ -190,11 +190,11 @@ tail /tmp/slack-token-refresh.log
190
190
 
191
191
  ### "No credentials found"
192
192
 
193
- Run `bunx @uniquedivine/mcp-slack@4.5.1 --doctor` to confirm diagnostic code, then `bunx @uniquedivine/mcp-slack@4.5.1 --setup` with Slack open in Chrome.
193
+ Run `bunx @uniquedivine/mcp-slack@4.5.2 --doctor` to confirm diagnostic code, then `bunx @uniquedivine/mcp-slack@4.5.2 --setup` with Slack open in Chrome.
194
194
 
195
195
  ### "invalid_auth" Error
196
196
 
197
- Tokens have expired. Run `bunx @uniquedivine/mcp-slack@4.5.1 --doctor` and follow the suggested next action.
197
+ Tokens have expired. Run `bunx @uniquedivine/mcp-slack@4.5.2 --doctor` and follow the suggested next action.
198
198
 
199
199
  ### MCP Server Not Loading
200
200
 
@@ -120,7 +120,7 @@ cat > ~/Library/LaunchAgents/com.slack-web-api.plist << 'EOF'
120
120
  <key>ProgramArguments</key>
121
121
  <array>
122
122
  <string>/Users/YOUR_USERNAME/.bun/bin/bunx</string>
123
- <string>@uniquedivine/mcp-slack@4.5.1</string>
123
+ <string>@uniquedivine/mcp-slack@4.5.2</string>
124
124
  <string>web</string>
125
125
  </array>
126
126
  <key>RunAtLoad</key>
package/lib/handlers.js CHANGED
@@ -14,7 +14,7 @@ import {
14
14
  isAutoRefreshAvailable,
15
15
  getLastExtractionError
16
16
  } from "./token-store.js";
17
- import { slackAPI, resolveUser, formatTimestamp, sleep, checkTokenHealth, getUserCacheStats } from "./slack-client.js";
17
+ import { slackAPI, resolveUser, formatTimestamp, sleep, checkTokenHealth, getUserCacheStats, manualRefreshAdvice } from "./slack-client.js";
18
18
  import {
19
19
  saveProfile as workflowSaveProfile,
20
20
  listProfiles as workflowListProfiles,
@@ -22,6 +22,7 @@ import {
22
22
  } from "./workflow-store.js";
23
23
  import { withRichMessageFields } from "./rich-message-fields.js";
24
24
  import { isAuthDeath, lifeboatResponse } from "./lifeboat.js";
25
+ import { withWriteLog } from "./write-log.js";
25
26
  import {
26
27
  checkOwnMessage,
27
28
  createRetryTracker,
@@ -140,7 +141,8 @@ export async function handleTokenStatus() {
140
141
  enabled: isAutoRefreshAvailable(),
141
142
  interval: "4 hours",
142
143
  last_attempt: health.refreshed ? "just_now" : null,
143
- requires: isAutoRefreshAvailable() ? "Slack tab open in Chrome" : "Not supported on this platform"
144
+ requires: isAutoRefreshAvailable() ? "Slack tab open in Chrome" : "Not supported on this platform",
145
+ manual_refresh: isAutoRefreshAvailable() ? null : manualRefreshAdvice()
144
146
  },
145
147
  cache: {
146
148
  users: cacheStats,
@@ -598,7 +600,7 @@ async function isGoneOnReread(channel, timestamp, selfId) {
598
600
  * before calling chat.delete, and maps known Slack errors to clear results.
599
601
  */
600
602
  export async function handleDeleteMessage(args) {
601
- return deleteMessage(args, { ignoreAge: false });
603
+ return withWriteLog("slack_delete_message", args, (recorder) => deleteMessage(args, { ignoreAge: false, recorder }));
602
604
  }
603
605
 
604
606
  /**
@@ -606,10 +608,10 @@ export async function handleDeleteMessage(args) {
606
608
  * age window, for deliberate cleanup of older messages.
607
609
  */
608
610
  export async function handleDeleteMessageUnsafe(args) {
609
- return deleteMessage(args, { ignoreAge: true });
611
+ return withWriteLog("slack_delete_message_unsafe", args, (recorder) => deleteMessage(args, { ignoreAge: true, recorder }));
610
612
  }
611
613
 
612
- async function deleteMessage(args, { ignoreAge }) {
614
+ async function deleteMessage(args, { ignoreAge, recorder }) {
613
615
  const invalid = validateTargetArgs(args);
614
616
  if (invalid) return invalid;
615
617
 
@@ -622,6 +624,7 @@ async function deleteMessage(args, { ignoreAge }) {
622
624
  ignoreAge,
623
625
  unsafeTool: "slack_delete_message_unsafe"
624
626
  });
627
+ recorder?.verify(ownership.verified);
625
628
  if (!ownership.ok) return ownership.result;
626
629
  const oldText = ownership.message.text ?? "";
627
630
 
@@ -677,7 +680,7 @@ async function deleteMessage(args, { ignoreAge }) {
677
680
  export const UPDATE_TEXT_MAX_CHARS = 4000;
678
681
 
679
682
  export async function handleUpdateMessage(args) {
680
- return updateMessage(args, { ignoreAge: false });
683
+ return withWriteLog("slack_update_message", args, (recorder) => updateMessage(args, { ignoreAge: false, recorder }));
681
684
  }
682
685
 
683
686
  /**
@@ -685,10 +688,10 @@ export async function handleUpdateMessage(args) {
685
688
  * age window, for deliberate cleanup of older messages.
686
689
  */
687
690
  export async function handleUpdateMessageUnsafe(args) {
688
- return updateMessage(args, { ignoreAge: true });
691
+ return withWriteLog("slack_update_message_unsafe", args, (recorder) => updateMessage(args, { ignoreAge: true, recorder }));
689
692
  }
690
693
 
691
- async function updateMessage(args, { ignoreAge }) {
694
+ async function updateMessage(args, { ignoreAge, recorder }) {
692
695
  const invalid = validateTargetArgs(args);
693
696
  if (invalid) return invalid;
694
697
  if (typeof args.text !== "string" || args.text.trim() === "") {
@@ -707,6 +710,7 @@ async function updateMessage(args, { ignoreAge }) {
707
710
  ignoreAge,
708
711
  unsafeTool: "slack_update_message_unsafe"
709
712
  });
713
+ recorder?.verify(ownership.verified);
710
714
  if (!ownership.ok) return ownership.result;
711
715
 
712
716
  const sessionChanged = sessionChangedResult(ownership, details);
package/lib/lifeboat.js CHANGED
@@ -15,9 +15,18 @@
15
15
  * - The long-form message is emitted at most once per process per hour;
16
16
  * subsequent failures inside that window get a one-line version so agents
17
17
  * in retry loops do not spam.
18
- * - Never reads or logs token values — it only inspects error codes.
18
+ * - Never reads or logs token values — it only inspects error codes and
19
+ * the credential source label.
20
+ * - The self-fix fits the setup. Credentials from SLACK_TOKEN/SLACK_COOKIE
21
+ * take precedence over the file --setup writes, so env users are told to
22
+ * update or unset those variables. Off macOS, where Chrome auto-heal and
23
+ * slack_refresh_tokens can't run, the advice is a manual refresh. macOS
24
+ * with file or keychain credentials keeps the original wording.
19
25
  */
20
26
 
27
+ import { platform as osPlatform } from "node:os";
28
+ import { loadTokensReadOnly } from "./token-store.js";
29
+
21
30
  // Slack API error codes (and the HTTP 401 case) that mean the session token
22
31
  // is dead and cannot be auto-healed — the point where the Lifeboat fires.
23
32
  export const AUTH_DEATH_SLACK_CODES = new Set([
@@ -46,6 +55,37 @@ export function resetLifeboatThrottle() {
46
55
  lastLongFormAt = 0;
47
56
  }
48
57
 
58
+ /**
59
+ * Recovery advice for this platform and credential source, or null for the
60
+ * default macOS wording.
61
+ */
62
+ export function recoveryAdvice({ platformName, credentialSource }) {
63
+ if (credentialSource === "environment") {
64
+ return {
65
+ selfFix:
66
+ `Your Slack credentials come from the SLACK_TOKEN and SLACK_COOKIE environment variables, which take precedence over the file \`${SETUP_CMD}\` writes. Update both with fresh values from a signed-in browser session, or unset both and run \`${SETUP_CMD}\`. Full steps: ${README_ANCHOR_URL}`,
67
+ nextAction:
68
+ `Update SLACK_TOKEN and SLACK_COOKIE with fresh values, or unset both and run \`${SETUP_CMD}\`. Running setup alone won't help while they're set.`,
69
+ };
70
+ }
71
+ if (platformName !== "darwin") {
72
+ return {
73
+ selfFix:
74
+ `Auto-refresh only runs on macOS, not ${platformName}. Sign in to Slack in your browser, then run \`${SETUP_CMD}\` to save fresh tokens. Full steps: ${README_ANCHOR_URL}`,
75
+ nextAction: `Sign in to Slack in your browser, then run \`${SETUP_CMD}\`.`,
76
+ };
77
+ }
78
+ return null;
79
+ }
80
+
81
+ function currentCredentialSource() {
82
+ try {
83
+ return loadTokensReadOnly()?.source ?? null;
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+
49
89
  function upsellEnabled() {
50
90
  return process.env.SLACK_MCP_NO_UPSELL !== "1";
51
91
  }
@@ -108,9 +148,26 @@ export function buildLifeboatPayload(err, options = {}) {
108
148
  const now = options?.now ?? Date.now();
109
149
  const slackError = authDeathCode(err);
110
150
  const upsell = upsellEnabled();
151
+ const advice = recoveryAdvice({
152
+ platformName: options?.platformName ?? osPlatform(),
153
+ credentialSource: options?.credentialSource !== undefined
154
+ ? options.credentialSource
155
+ : currentCredentialSource(),
156
+ });
111
157
 
112
158
  const throttled = lastLongFormAt > 0 && now - lastLongFormAt < THROTTLE_WINDOW_MS;
113
159
 
160
+ if (throttled && advice) {
161
+ return {
162
+ status: "error",
163
+ code: "slack_auth_expired",
164
+ slack_error: slackError,
165
+ throttled: true,
166
+ message: `Slack session token is still expired or revoked. ${advice.nextAction}`,
167
+ next_action: advice.nextAction,
168
+ };
169
+ }
170
+
114
171
  if (throttled) {
115
172
  const message = upsell
116
173
  ? `Slack session token is still expired or revoked. Re-extract with \`${SETUP_CMD}\`. Permanent fix (hosted OAuth, free tier): ${HOSTED_SETUP_URL}`
@@ -143,12 +200,20 @@ export function buildLifeboatPayload(err, options = {}) {
143
200
  payload.extraction_error = err.extraction_error;
144
201
  }
145
202
 
203
+ if (advice) {
204
+ payload.self_fix = advice.selfFix;
205
+ }
206
+
146
207
  if (upsell) {
147
208
  payload.hosted_option =
148
209
  `To stop re-extracting every 1-2 weeks, switch to hosted OAuth (it never rotates): ${HOSTED_SETUP_URL} — free tier available, no credit card.`;
149
- payload.next_action = `Run \`${SETUP_CMD}\` to re-extract tokens, or switch to permanent hosted OAuth (see hosted_option).`;
210
+ payload.next_action = advice
211
+ ? `${advice.nextAction} Or switch to permanent hosted OAuth (see hosted_option).`
212
+ : `Run \`${SETUP_CMD}\` to re-extract tokens, or switch to permanent hosted OAuth (see hosted_option).`;
150
213
  } else {
151
- payload.next_action = `Run \`${SETUP_CMD}\` to re-extract tokens (macOS: call the slack_refresh_tokens tool).`;
214
+ payload.next_action = advice
215
+ ? advice.nextAction
216
+ : `Run \`${SETUP_CMD}\` to re-extract tokens (macOS: call the slack_refresh_tokens tool).`;
152
217
  }
153
218
 
154
219
  return payload;
@@ -51,6 +51,10 @@ export const SLACK_WRITE_ERRORS = Object.freeze({
51
51
  message: "The Slack session changed after the ownership check, so the tool didn't send the change.",
52
52
  next_action: "Run slack_health_check to confirm the signed-in user, then call the tool again."
53
53
  },
54
+ message_deleted: {
55
+ message: "The message was already deleted. Only Slack's \"This message was deleted.\" placeholder remains at that timestamp, above its thread replies.",
56
+ next_action: "Nothing to change. If you meant another message, read the thread with slack_get_thread to get its timestamp."
57
+ },
54
58
  lookup_incomplete: {
55
59
  message: "The tool couldn't finish searching the thread for this message, so it didn't make the change.",
56
60
  next_action: "Check the timestamp with slack_get_thread and call the tool again."
@@ -101,6 +105,10 @@ export const MAX_REPLY_PAGES = 50;
101
105
 
102
106
  const SLACK_TS_PATTERN = /^\d+\.\d+$/;
103
107
 
108
+ // Slack conversation IDs: C (channel), D (DM), or G (private channel or
109
+ // group DM), then at least 8 uppercase letters or digits.
110
+ export const SLACK_CONVERSATION_ID_PATTERN = /^[CDG][A-Z0-9]{8,}$/;
111
+
104
112
  /**
105
113
  * Build an invalid_argument error result for one input field.
106
114
  */
@@ -119,8 +127,8 @@ export function invalidArgument(field, message) {
119
127
  export function validateTargetArgs(args) {
120
128
  const input = args && typeof args === "object" ? args : {};
121
129
  const { channel_id: channelId, timestamp, expected_text: expectedText } = input;
122
- if (typeof channelId !== "string" || channelId.trim() === "" || /\s/.test(channelId)) {
123
- return invalidArgument("channel_id", "channel_id must be a non-empty channel or DM ID with no spaces.");
130
+ if (typeof channelId !== "string" || !SLACK_CONVERSATION_ID_PATTERN.test(channelId)) {
131
+ return invalidArgument("channel_id", "channel_id must be a Slack channel or DM ID, such as C0123456789 or D0123456789.");
124
132
  }
125
133
  if (typeof timestamp !== "string" || !SLACK_TS_PATTERN.test(timestamp)) {
126
134
  return invalidArgument("timestamp", "timestamp must be a Slack message timestamp such as \"1767368030.607599\".");
@@ -252,7 +260,15 @@ export function isGoneForSelf(message, selfId) {
252
260
  * Returns { ok: true, message, selfId, sessionToken } or
253
261
  * { ok: false, result } where result is a ready MCP error. Pass the result
254
262
  * to sessionChangedResult just before the write.
263
+ *
264
+ * `verified` says what Slack confirmed: the channel once conversations.history
265
+ * answered for it, and the timestamp once the message was found. It's absent
266
+ * for refusals made before any Slack call. The write log uses it so only
267
+ * Slack-confirmed IDs reach stderr.
255
268
  */
269
+ const CHANNEL_VERIFIED = Object.freeze({ channel: true, timestamp: false });
270
+ const MESSAGE_VERIFIED = Object.freeze({ channel: true, timestamp: true });
271
+
256
272
  export async function checkOwnMessage(channelId, timestamp, options = {}) {
257
273
  const {
258
274
  expectedText,
@@ -291,17 +307,23 @@ export async function checkOwnMessage(channelId, timestamp, options = {}) {
291
307
  ]);
292
308
  } catch (error) {
293
309
  if (error?.message === "lookup_incomplete") {
294
- return { ok: false, result: messageWriteError("lookup_incomplete", details) };
310
+ return { ok: false, verified: CHANNEL_VERIFIED, result: messageWriteError("lookup_incomplete", details) };
295
311
  }
296
312
  throw error;
297
313
  }
298
314
 
299
315
  if (!message) {
300
- return { ok: false, result: messageWriteError("message_not_found", details) };
316
+ return { ok: false, verified: CHANNEL_VERIFIED, result: messageWriteError("message_not_found", details) };
317
+ }
318
+ // A deleted thread parent leaves a tombstone at the same ts, authored by
319
+ // Slack rather than the user; report it as deleted, not as someone else's.
320
+ if (message.subtype === "tombstone") {
321
+ return { ok: false, verified: MESSAGE_VERIFIED, result: messageWriteError("message_deleted", details) };
301
322
  }
302
323
  if (message.user !== selfId) {
303
324
  return {
304
325
  ok: false,
326
+ verified: MESSAGE_VERIFIED,
305
327
  result: messageWriteError("not_own_message", {
306
328
  ...details,
307
329
  author: message.user || message.bot_id || null
@@ -314,13 +336,14 @@ export async function checkOwnMessage(channelId, timestamp, options = {}) {
314
336
  if (typeof expectedText !== "string" || (message.text ?? "").trim() !== expectedText.trim()) {
315
337
  return {
316
338
  ok: false,
339
+ verified: MESSAGE_VERIFIED,
317
340
  result: messageWriteError("text_mismatch", details, {
318
341
  message: "expected_text doesn't match the message's current text, so the tool won't change it.",
319
342
  next_action: "Read the message again with slack_conversations_history or slack_get_thread and confirm it's the one the user meant."
320
343
  })
321
344
  };
322
345
  }
323
- return { ok: true, message, selfId, sessionToken };
346
+ return { ok: true, verified: MESSAGE_VERIFIED, message, selfId, sessionToken };
324
347
  }
325
348
 
326
349
  /**
@@ -15,7 +15,9 @@ import {
15
15
  extractFromChrome,
16
16
  getLastExtractionError,
17
17
  saveAutoHealTelemetry,
18
+ isAutoRefreshAvailable,
18
19
  } from "./token-store.js";
20
+ import { platform as osPlatform } from "node:os";
19
21
 
20
22
  // ============ Configuration ============
21
23
 
@@ -97,11 +99,29 @@ const userCache = new LRUCache(USER_CACHE_MAX_SIZE, USER_CACHE_TTL);
97
99
  // ============ Token Health ============
98
100
 
99
101
  /**
100
- * Check token health and attempt proactive refresh if needed
102
+ * How to refresh the session token by hand, for platforms where Chrome
103
+ * auto-heal can't run.
101
104
  */
102
- export async function checkTokenHealth(logger = console) {
105
+ export function manualRefreshAdvice(platformName = osPlatform()) {
106
+ return `Auto-refresh only runs on macOS, not ${platformName}. To refresh by hand, sign in to Slack in your browser, then run bunx @uniquedivine/mcp-slack --setup, or update SLACK_TOKEN and SLACK_COOKIE.`;
107
+ }
108
+
109
+ /**
110
+ * Check token health and attempt proactive refresh if needed.
111
+ *
112
+ * Options (for tests): autoHealAvailable defaults to isAutoRefreshAvailable(),
113
+ * platformName to os.platform(), and creds to the stored credentials. Where auto-heal can't run, the check
114
+ * skips the Chrome refresh, never reports auto-heal as failing or stuck, and
115
+ * gives manual-refresh advice with the token-age warning.
116
+ */
117
+ export async function checkTokenHealth(logger = console, options = {}) {
118
+ const {
119
+ autoHealAvailable = isAutoRefreshAvailable(),
120
+ platformName = osPlatform(),
121
+ creds: injectedCreds
122
+ } = options;
103
123
  const silentLogger = { error: () => {}, warn: () => {}, log: () => {} };
104
- const creds = loadTokens(false, silentLogger, { autoExtract: false });
124
+ const creds = injectedCreds ?? loadTokens(false, silentLogger, { autoExtract: false });
105
125
 
106
126
  if (!creds) {
107
127
  return {
@@ -120,13 +140,15 @@ export async function checkTokenHealth(logger = console) {
120
140
  ? Math.round(tokenAge / (60 * 60 * 1000) * 10) / 10
121
141
  : null;
122
142
 
123
- // Read auto-heal telemetry (only populated when source is "file")
124
- let lastAutoHealAttempt = creds.lastAutoHealAttempt || null;
125
- let lastAutoHealError = creds.lastAutoHealError || null;
126
- let stuckSince = creds.stuckSince || null;
143
+ // Read auto-heal telemetry (only populated when source is "file"). Where
144
+ // auto-heal can't run, older telemetry such as unsupported_platform isn't
145
+ // a failure, so it's ignored.
146
+ let lastAutoHealAttempt = autoHealAvailable ? creds.lastAutoHealAttempt || null : null;
147
+ let lastAutoHealError = autoHealAvailable ? creds.lastAutoHealError || null : null;
148
+ let stuckSince = autoHealAvailable ? creds.stuckSince || null : null;
127
149
 
128
150
  // Attempt proactive refresh if token is getting old
129
- if (hasKnownAge && tokenAge > TOKEN_WARNING_AGE && Date.now() - lastRefreshAttempt > REFRESH_COOLDOWN) {
151
+ if (autoHealAvailable && hasKnownAge && tokenAge > TOKEN_WARNING_AGE && Date.now() - lastRefreshAttempt > REFRESH_COOLDOWN) {
130
152
  lastRefreshAttempt = Date.now();
131
153
  const attemptAt = new Date().toISOString();
132
154
  logger.error?.(`Token is ${ageHours}h old, attempting proactive refresh...`);
@@ -162,7 +184,8 @@ export async function checkTokenHealth(logger = console) {
162
184
  }
163
185
 
164
186
  const stuckSinceMs = stuckSince ? new Date(stuckSince).getTime() : Number.NaN;
165
- const isStuck = Number.isFinite(stuckSinceMs)
187
+ const isStuck = autoHealAvailable
188
+ && Number.isFinite(stuckSinceMs)
166
189
  && (Date.now() - stuckSinceMs) > STUCK_THRESHOLD_MS
167
190
  && !!lastAutoHealError;
168
191
 
@@ -187,14 +210,19 @@ export async function checkTokenHealth(logger = console) {
187
210
  last_auto_heal_attempt: lastAutoHealAttempt,
188
211
  last_auto_heal_error: lastAutoHealError,
189
212
  stuck_since: stuckSince,
213
+ auto_heal_available: autoHealAvailable,
190
214
  message: isStuck
191
215
  ? `Auto-heal has been failing since ${stuckSince} (last error: ${lastAutoHealError}). Open Chrome > View > Developer > Allow JavaScript from Apple Events, then run npm run tokens:auto.`
192
216
  : !hasKnownAge
193
217
  ? 'Token age unknown (missing timestamp) - auth can still be valid'
194
218
  : tokenAge > TOKEN_CRITICAL_AGE
195
- ? 'Token may expire soon - open Slack in Chrome'
219
+ ? (autoHealAvailable
220
+ ? 'Token may expire soon - open Slack in Chrome'
221
+ : `Token may expire soon. ${manualRefreshAdvice(platformName)}`)
196
222
  : tokenAge > TOKEN_WARNING_AGE
197
- ? 'Token is getting old - will auto-refresh if Slack tab is open'
223
+ ? (autoHealAvailable
224
+ ? 'Token is getting old - will auto-refresh if Slack tab is open'
225
+ : `Token is getting old. ${manualRefreshAdvice(platformName)}`)
198
226
  : 'Token is healthy'
199
227
  };
200
228
  }
@@ -295,6 +323,20 @@ export async function slackAPI(method, params = {}, options = {}) {
295
323
  }
296
324
 
297
325
  // Handle auth errors with auto-retry
326
+ if ((data.error === "invalid_auth" || data.error === "token_expired") && retryOnAuthFail && !isAutoRefreshAvailable()) {
327
+ // Chrome auto-heal can't run here, so don't try it or record it as a
328
+ // failure; point to the manual refresh instead.
329
+ const err = new Error(`Slack auth failed (${data.error}). ${manualRefreshAdvice()}`);
330
+ err.code = 'token_auth_failed';
331
+ err.slack_error = data.error;
332
+ err.extraction_error = {
333
+ code: 'unsupported_platform',
334
+ message: 'Chrome auto-extraction is only available on macOS.',
335
+ detail: null
336
+ };
337
+ err.next_action = manualRefreshAdvice();
338
+ throw err;
339
+ }
298
340
  if ((data.error === "invalid_auth" || data.error === "token_expired") && retryOnAuthFail) {
299
341
  logger.error?.("Token expired, attempting Chrome auto-extraction...");
300
342
  const attemptAt = new Date().toISOString();
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Write Log
3
+ *
4
+ * One structured stderr line per edit or delete attempt, so changes to Slack
5
+ * messages leave a local record beyond the agent's chat. The line carries
6
+ * only identifiers and outcome codes: never tokens, cookies, or message text.
7
+ *
8
+ * channel_id and timestamp come from the agent, so their shape proves
9
+ * nothing: "C0NF1DENT1AL" looks like a channel ID. The log writes the channel
10
+ * only after Slack answered conversations.history for it, and the timestamp
11
+ * only after Slack returned that message. Otherwise both are null, and so is
12
+ * age_hours, since it comes from the timestamp.
13
+ *
14
+ * Format:
15
+ * slack-mcp write {"tool":"slack_delete_message","channel":"D0123","timestamp":"1794916496.123799","status":"deleted","code":null,"age_hours":0.2}
16
+ */
17
+
18
+ import { SLACK_CONVERSATION_ID_PATTERN } from "./message-ownership.js";
19
+
20
+ const LOG_PREFIX = "slack-mcp write";
21
+ const TS_PATTERN = /^\d{1,12}\.\d{1,9}$/;
22
+ const CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
23
+
24
+ let sink = (line) => console.error(line);
25
+
26
+ /**
27
+ * Replace where log lines go. Returns the previous sink so tests can restore
28
+ * it.
29
+ */
30
+ export function setWriteLogSink(next) {
31
+ const previous = sink;
32
+ sink = next;
33
+ return previous;
34
+ }
35
+
36
+ // The shape checks are a second guard; Slack verification is the main one.
37
+ function safeChannel(value) {
38
+ return typeof value === "string" && SLACK_CONVERSATION_ID_PATTERN.test(value) ? value : null;
39
+ }
40
+
41
+ function safeTimestamp(value) {
42
+ return typeof value === "string" && TS_PATTERN.test(value) ? value : null;
43
+ }
44
+
45
+ function safeCode(value) {
46
+ return typeof value === "string" && CODE_PATTERN.test(value) ? value : null;
47
+ }
48
+
49
+ /**
50
+ * Message age in hours, to one decimal, or null for an invalid timestamp.
51
+ */
52
+ export function ageHours(timestamp, now = Date.now()) {
53
+ const ts = safeTimestamp(timestamp);
54
+ if (!ts) return null;
55
+ return Math.round(((now - Number(ts) * 1000) / 3_600_000) * 10) / 10;
56
+ }
57
+
58
+ /**
59
+ * Status and error code from a tool result. The result's text is JSON that
60
+ * may include message text, so only the status and code fields are read.
61
+ */
62
+ function outcomeOf(result) {
63
+ try {
64
+ const payload = JSON.parse(result?.content?.[0]?.text ?? "{}");
65
+ return {
66
+ status: safeCode(payload.status) ?? (result?.isError ? "error" : null),
67
+ code: safeCode(payload.code)
68
+ };
69
+ } catch {
70
+ return { status: result?.isError ? "error" : null, code: null };
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Build the log line for one attempt. Pure, for tests.
76
+ */
77
+ export function formatWriteLogLine({ tool, args, status, code, verified, now = Date.now() }) {
78
+ const entry = {
79
+ tool: safeCode(tool),
80
+ channel: verified?.channel ? safeChannel(args?.channel_id) : null,
81
+ timestamp: verified?.timestamp ? safeTimestamp(args?.timestamp) : null,
82
+ status: safeCode(status),
83
+ code: safeCode(code),
84
+ age_hours: verified?.timestamp ? ageHours(args?.timestamp, now) : null
85
+ };
86
+ return `${LOG_PREFIX} ${JSON.stringify(entry)}`;
87
+ }
88
+
89
+ /**
90
+ * Run a write handler and log one line for the attempt, whether it returns a
91
+ * result or throws. The handler receives a recorder and calls
92
+ * `recorder.verify(ownership.verified)` with what Slack confirmed.
93
+ */
94
+ export async function withWriteLog(tool, args, run) {
95
+ const recorder = {
96
+ verified: null,
97
+ verify(verified) {
98
+ if (verified) recorder.verified = verified;
99
+ }
100
+ };
101
+ let result;
102
+ try {
103
+ result = await run(recorder);
104
+ } catch (error) {
105
+ // A thrown Slack error's message is its code, such as invalid_auth.
106
+ logSafely({ tool, args, status: "thrown", code: error?.message, verified: recorder.verified });
107
+ throw error;
108
+ }
109
+ logSafely({ tool, args, ...outcomeOf(result), verified: recorder.verified });
110
+ return result;
111
+ }
112
+
113
+ function logSafely(entry) {
114
+ try {
115
+ sink(formatWriteLogLine(entry));
116
+ } catch {
117
+ // Logging must never change the tool's outcome.
118
+ }
119
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@uniquedivine/mcp-slack",
3
3
  "mcpName": "io.github.unique-divine/mcp-slack",
4
- "version": "4.5.1",
4
+ "version": "4.5.2",
5
5
  "description": "Slack MCP server maintained in Jiyuu",
6
6
  "type": "module",
7
7
  "main": "src/server.js",
package/server.json CHANGED
@@ -18,12 +18,12 @@
18
18
  "source": "github",
19
19
  "subfolder": "mcp/slack"
20
20
  },
21
- "version": "4.5.1",
21
+ "version": "4.5.2",
22
22
  "packages": [
23
23
  {
24
24
  "registryType": "npm",
25
25
  "identifier": "@uniquedivine/mcp-slack",
26
- "version": "4.5.1",
26
+ "version": "4.5.2",
27
27
  "transport": {
28
28
  "type": "stdio"
29
29
  },