yt-slack-mcp 0.5.0 → 0.7.0

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
@@ -7,11 +7,13 @@ A host-agnostic [Model Context Protocol](https://modelcontextprotocol.io) server
7
7
  - Read Slack channel history and thread replies.
8
8
  - Read message permalinks from channels, DMs, and group DMs.
9
9
  - Return image attachments inline, extract text from PDFs, and return `text/*` attachment contents inline.
10
+ - Save any attachment to a local path from a message permalink, file permalink, or file ID, preserving the original bytes and reporting the saved path, filename, and MIME type.
10
11
  - Retrieve private attachment contents through the authenticated Slack browser session.
11
12
  - Reply to a thread, add or remove a reaction, edit an authored message or thread reply, or upload local files only in explicitly allowed channel IDs.
12
- - Prefix every message the agent posts with `🤖:` — or `🤖 <model>:` when the call names the model — so agent replies stand apart from the account's own messages; an edit can opt out with `agent_authored: false`.
13
+ - Have no plain top-level text post: a reply needs an existing thread, and a file upload with an `initial_comment` is the only way to start a top-level message.
14
+ - Prefix every message the agent posts with `🤖:` — or `🤖 <backend model ID>:` when the call names the model — so agent replies stand apart from the account's own messages; an edit can opt out with `agent_authored: false`.
13
15
 
14
- Attachment limits: images and text files are limited to 10 MB; text attachments are truncated at 100,000 characters. PDFs are limited to 20 MB, 50 pages, and 100,000 extracted characters.
16
+ Attachment limits: images and text files are limited to 10 MB; text attachments are truncated at 100,000 characters. PDFs are limited to 20 MB, 50 pages, and 100,000 extracted characters. These limits apply to content returned inline; `slack_save_file` streams the attachment unchanged to disk.
15
17
 
16
18
  ## Tools
17
19
 
@@ -19,12 +21,14 @@ Attachment limits: images and text files are limited to 10 MB; text attachments
19
21
  |------|-------------|
20
22
  | `slack_read_permalink` | Read a message or thread from a channel, DM, or group-DM permalink, including supported attachments. |
21
23
  | `slack_get_replies` | Read replies for a thread by channel ID and timestamp. |
22
- | `slack_get_history` | Read recent channel history. |
23
- | `slack_reply_to_thread` | Reply to a thread, with optional `model`, in a `🤖:`-prefixed message; restricted to allowed channels. |
24
+ | `slack_get_history` | Read recent channel history by channel ID (up to 200 messages). |
25
+ | `slack_get_history` | Read recent channel history by channel ID (up to 200 messages). |
26
+ | `slack_save_file` | Save a file attached to a message to a local path from a Slack message permalink, file permalink, or file ID, preserving the original bytes; the destination's parent directory must exist, and a destination that is an existing directory keeps the attachment's filename (replacing characters the local filesystem rejects) and refuses to overwrite an existing file — pass an explicit file path to overwrite; returns the saved path, filename, and MIME type. |
27
+ | `slack_reply_to_thread` | Reply to a thread, with `model` set to the backend model ID when known, in a `🤖:`-prefixed message; restricted to allowed channels. |
24
28
  | `slack_add_reaction` | Add a reaction; restricted to allowed channels. |
25
29
  | `slack_remove_reaction` | Remove a reaction added by this account; restricted to allowed channels. |
26
- | `slack_upload_files` | Upload up to 10 local files to a channel or thread, with an optional `initial_comment` prefixed with `🤖:` and an optional `model` (only used with a comment); returns file and message permalinks; restricted to allowed channels. |
27
- | `slack_edit_message` | Edit an authored message or thread reply by channel ID and timestamp; replaces the message text with `🤖:`-prefixed text and an optional `model`, or with the text as given when `agent_authored` is `false` (Slack removes any existing Block Kit blocks) and returns the updated timestamp and permalink; restricted to allowed channels. |
30
+ | `slack_upload_files` | Upload up to 10 local files (10 MB each) to a channel or thread, with an optional `initial_comment` prefixed with `🤖:` and `model` set to the backend model ID when known (only used with a comment); returns file and message permalinks; restricted to allowed channels. |
31
+ | `slack_edit_message` | Edit an authored message or thread reply by channel ID and timestamp; replaces the message text with `🤖:`-prefixed text and `model` set to the backend model ID when known, or with the text as given when `agent_authored` is `false` (Slack removes any existing Block Kit blocks) and returns the updated timestamp and permalink; restricted to allowed channels. |
28
32
 
29
33
  ## Agent message prefix
30
34
 
@@ -36,13 +40,17 @@ text of every posted message is prefixed with `🤖:` by default:
36
40
  🤖: deployed revision 4f2c1a9
37
41
  ```
38
42
 
39
- The MCP transport does not report which model is calling, so a write tool call
40
- can pass `model` with the model it is running; the prefix then names it:
43
+ The MCP transport does not report which model is calling, so a write call passes
44
+ `model` with the backend model ID it is running — for example
45
+ `claude-sonnet-4-5`, not a display name — and the prefix then names it:
41
46
 
42
47
  ```text
43
48
  🤖 claude-sonnet-4-5: deployed revision 4f2c1a9
44
49
  ```
45
50
 
51
+ The parameter stays optional for a client that cannot determine its own model
52
+ ID; without it the prefix is the bare `🤖:`.
53
+
46
54
  The prefix is added once: text that already starts with `🤖` is sent unchanged,
47
55
  so editing a prefixed message does not stack prefixes. A file upload without an
48
56
  `initial_comment` — or with only whitespace — gets no comment rather than a bare
@@ -71,12 +79,12 @@ Save each token as a single-line file:
71
79
  ~/.config/yt-slack-mcp/secrets/slack-xoxd.txt
72
80
  ```
73
81
 
74
- The server reads these paths by default. Override them with the config file or environment variables if your MCP host manages secrets elsewhere.
82
+ The server reads these paths by default. Override them in the config file described below if your MCP host manages secrets elsewhere.
75
83
 
76
84
  ### 3. (Optional) Configure allowed write channels and paths
77
85
 
78
- All configuration can live in a JSON config file at
79
- `~/.config/yt-slack-mcp/config.json` (override with `SLACK_MCP_CONFIG`):
86
+ All configuration lives in a JSON config file at
87
+ `~/.config/yt-slack-mcp/config.json`:
80
88
 
81
89
  ```json
82
90
  {
@@ -90,22 +98,27 @@ All configuration can live in a JSON config file at
90
98
 
91
99
  By default the write tools (`slack_reply_to_thread`, `slack_add_reaction`,
92
100
  `slack_remove_reaction`, `slack_edit_message`) and `slack_upload_files` are
93
- locked down — no channel is writable. Each upload is limited to 10 MB. Every
94
- field is optional; a missing file just means defaults. Env vars always override
95
- the config file.
101
+ locked down — no channel is writable. Each uploaded file is limited to 10 MB, and
102
+ a call accepts at most 10 files. Every field is optional; a missing file just
103
+ means defaults.
96
104
 
97
105
  ## Configuration
98
106
 
99
- Config resolution order: built-in defaults → config file → env vars.
107
+ Configuration comes from the JSON config file, with built-in defaults for
108
+ absent keys.
109
+
110
+ | Config key | Default | Description |
111
+ |------------|---------|-------------|
112
+ | `secretsDir` | `~/.config/yt-slack-mcp/secrets` | Directory holding the token files |
113
+ | `xoxcPath` | `$SECRETS_DIR/slack-xoxc.txt` | Path to the `xoxc` token |
114
+ | `xoxdPath` | `$SECRETS_DIR/slack-xoxd.txt` | Path to the `xoxd` token |
115
+ | `allowedWriteChannels` | *(none)* | Channel IDs allowed for write tools |
116
+ | `userAgent` | `Mozilla/5.0` | HTTP `User-Agent` header |
100
117
 
101
- | Config file key | Env var | Default | Description |
102
- |-----------------|---------|---------|-------------|
103
- | `secretsDir` | `SLACK_MCP_SECRETS_DIR` | `~/.config/yt-slack-mcp/secrets` | Directory holding the token files |
104
- | `xoxcPath` | `SLACK_MCP_XOXC_PATH` | `$SECRETS_DIR/slack-xoxc.txt` | Path to the `xoxc` token |
105
- | `xoxdPath` | `SLACK_MCP_XOXD_PATH` | `$SECRETS_DIR/slack-xoxd.txt` | Path to the `xoxd` token |
106
- | `allowedWriteChannels` | `SLACK_MCP_ALLOWED_WRITE_CHANNELS` | *(none)* | Channel IDs allowed for write tools (comma-separated in env) |
107
- | `userAgent` | `SLACK_MCP_USER_AGENT` | `Mozilla/5.0` | HTTP `User-Agent` header |
108
- | *(config file path)* | `SLACK_MCP_CONFIG` | `~/.config/yt-slack-mcp/config.json` | Path to the JSON config file |
118
+ Environment-variable configuration has been removed. Move any environment-supplied
119
+ values into `~/.config/yt-slack-mcp/config.json`; the config path is fixed for the
120
+ CLI. `allowedWriteChannels` accepts an array or a comma-separated string, so an
121
+ old comma-separated value can be copied as-is.
109
122
 
110
123
  ## MCP host configuration
111
124
 
@@ -128,6 +141,14 @@ For example, Claude Desktop uses:
128
141
  }
129
142
  ```
130
143
 
144
+ ## Install as a skill
145
+
146
+ [`skills/slack-mcp/SKILL.md`](skills/slack-mcp/SKILL.md) packages this server as
147
+ an Agent Skill so an agent knows when to read Slack, when a write is allowed,
148
+ and which tool fits the request. Copy or symlink the `skills/slack-mcp`
149
+ directory into your agent's skills directory (for example
150
+ `.agents/skills/slack-mcp`); the server still needs the setup above.
151
+
131
152
  ## License
132
153
 
133
154
  MIT
package/index.js CHANGED
@@ -12,14 +12,19 @@ import {
12
12
  } from "@modelcontextprotocol/sdk/types.js";
13
13
  import { z } from "zod";
14
14
  import { zodToJsonSchema } from "zod-to-json-schema";
15
+ import { randomUUID } from "crypto";
15
16
  import fs from "fs";
16
17
  import os from "os";
17
18
  import path from "path";
19
+ import { Readable } from "stream";
20
+ import { pipeline } from "stream/promises";
18
21
  import { fileURLToPath } from "url";
19
22
 
20
23
 
21
24
  const DEFAULT_SECRETS_DIR = path.join(os.homedir(), ".config", "yt-slack-mcp", "secrets");
22
25
  const DEFAULT_CONFIG_PATH = path.join(os.homedir(), ".config", "yt-slack-mcp", "config.json");
26
+ const PACKAGE_INFO = JSON.parse(fs.readFileSync(new URL("./package.json", import.meta.url), "utf8"));
27
+ const SERVER_INFO = { name: "yt-slack-mcp", version: PACKAGE_INFO.version };
23
28
 
24
29
  const maxImageBytes = 10 * 1024 * 1024;
25
30
  const maxPdfBytes = 20 * 1024 * 1024;
@@ -28,6 +33,8 @@ const maxPdfTextCharacters = 100_000;
28
33
  const maxTextFileBytes = 10 * 1024 * 1024;
29
34
  const maxTextFileCharacters = 100_000;
30
35
  const maxUploadBytes = 10 * 1024 * 1024;
36
+ const threadPageSize = 200;
37
+ const maxThreadPages = 10;
31
38
 
32
39
  function expandHome(filePath) {
33
40
  if (!filePath) {
@@ -46,14 +53,29 @@ function parseChannelList(value) {
46
53
  if (value === undefined || value === null || value === "") {
47
54
  return null;
48
55
  }
49
- return value
50
- .split(",")
51
- .map((c) => c.trim())
56
+ const list = Array.isArray(value)
57
+ ? value
58
+ : typeof value === "string"
59
+ ? value.split(",")
60
+ : null;
61
+ if (list === null) {
62
+ throw new Error("channel IDs must be an array or a comma-separated string");
63
+ }
64
+ return list
65
+ .map((channel) => {
66
+ if (typeof channel !== "string") {
67
+ throw new Error("channel IDs must be strings");
68
+ }
69
+ return channel.trim();
70
+ })
52
71
  .filter(Boolean);
53
72
  }
54
73
 
55
- function loadConfig(env = process.env) {
56
- const configPath = env.SLACK_MCP_CONFIG || DEFAULT_CONFIG_PATH;
74
+ function loadConfig(input = DEFAULT_CONFIG_PATH) {
75
+ const configPath =
76
+ typeof input === "string"
77
+ ? input
78
+ : input?.SLACK_MCP_CONFIG || DEFAULT_CONFIG_PATH;
57
79
  let fileConfig = {};
58
80
  if (fs.existsSync(configPath)) {
59
81
  try {
@@ -63,19 +85,44 @@ function loadConfig(env = process.env) {
63
85
  }
64
86
  }
65
87
 
66
- const secretsDir =
67
- env.SLACK_MCP_SECRETS_DIR || expandHome(fileConfig.secretsDir) || DEFAULT_SECRETS_DIR;
68
- const xoxcPath =
69
- env.SLACK_MCP_XOXC_PATH || expandHome(fileConfig.xoxcPath) || path.join(secretsDir, "slack-xoxc.txt");
70
- const xoxdPath =
71
- env.SLACK_MCP_XOXD_PATH || expandHome(fileConfig.xoxdPath) || path.join(secretsDir, "slack-xoxd.txt");
72
- const allowedWriteChannels =
73
- parseChannelList(env.SLACK_MCP_ALLOWED_WRITE_CHANNELS) ?? fileConfig.allowedWriteChannels ?? [];
74
- const userAgent = env.SLACK_MCP_USER_AGENT || fileConfig.userAgent || "Mozilla/5.0";
88
+ const secretsDir = expandHome(fileConfig.secretsDir) || DEFAULT_SECRETS_DIR;
89
+ const xoxcPath = expandHome(fileConfig.xoxcPath) || path.join(secretsDir, "slack-xoxc.txt");
90
+ const xoxdPath = expandHome(fileConfig.xoxdPath) || path.join(secretsDir, "slack-xoxd.txt");
91
+ let allowedWriteChannels;
92
+ try {
93
+ allowedWriteChannels = parseChannelList(fileConfig.allowedWriteChannels) ?? [];
94
+ } catch (e) {
95
+ throw new Error(`invalid Slack MCP config ${configPath}: ${e.message}`);
96
+ }
97
+ const userAgent = fileConfig.userAgent || "Mozilla/5.0";
75
98
 
76
99
  return { configPath, secretsDir, xoxcPath, xoxdPath, allowedWriteChannels, userAgent };
77
100
  }
78
101
 
102
+ function legacyEnvDiagnostic(env = process.env) {
103
+ const mappings = [
104
+ ["SLACK_MCP_SECRETS_DIR", "secretsDir"],
105
+ ["SLACK_MCP_XOXC_PATH", "xoxcPath"],
106
+ ["SLACK_MCP_XOXD_PATH", "xoxdPath"],
107
+ ["SLACK_MCP_ALLOWED_WRITE_CHANNELS", "allowedWriteChannels"],
108
+ ["SLACK_MCP_USER_AGENT", "userAgent"],
109
+ ]
110
+ .filter(([key]) => typeof env[key] === "string" && env[key].trim() !== "")
111
+ .map(([key, configKey]) => ` ${key} -> "${configKey}"`);
112
+ if (typeof env.SLACK_MCP_CONFIG === "string" && env.SLACK_MCP_CONFIG.trim() !== "") {
113
+ mappings.push(` SLACK_MCP_CONFIG -> ignored; the config path is fixed at ${DEFAULT_CONFIG_PATH}`);
114
+ }
115
+ if (mappings.length === 0) {
116
+ return null;
117
+ }
118
+ return [
119
+ "Warning: obsolete Slack MCP environment configuration detected. Environment-variable configuration has been removed and is ignored.",
120
+ `Move these settings into ${DEFAULT_CONFIG_PATH} and remove the variables from your MCP host environment:`,
121
+ ...mappings,
122
+ "Write tools stay deny-by-default until allowedWriteChannels is configured in the config file.",
123
+ ].join("\n");
124
+ }
125
+
79
126
  function readSecret(filePath, label) {
80
127
  if (!fs.existsSync(filePath)) {
81
128
  throw new Error(`missing ${label} (looked at ${filePath})`);
@@ -230,6 +277,86 @@ function createSlackClient({ xoxcToken, xoxdToken, userAgent = "Mozilla/5.0" })
230
277
  return text;
231
278
  };
232
279
 
280
+ const resolveMessageFile = async ({ channelId, timestamp, threadTs }) => {
281
+ const rootTs = threadTs || timestamp;
282
+ let cursor;
283
+ let pages = 0;
284
+ const seenCursors = new Set();
285
+ for (;;) {
286
+ pages += 1;
287
+ let response;
288
+ try {
289
+ response = await slackApi("conversations.replies", {
290
+ channel: channelId,
291
+ ts: rootTs,
292
+ limit: String(threadPageSize),
293
+ cursor,
294
+ });
295
+ } catch (error) {
296
+ const reason = String(error?.message ?? error);
297
+ if (/ratelimit|rate_limited/i.test(reason)) {
298
+ throw new Error(
299
+ `${reason}. Retry later, or pass a Slack file ID or file permalink to skip the thread lookup.`
300
+ );
301
+ }
302
+ throw error;
303
+ }
304
+ const message = (response.messages || []).find((item) => item.ts === timestamp);
305
+ if (message) {
306
+ const files = message.files || [];
307
+ if (!files.length) {
308
+ throw new Error(`no files attached to message ${timestamp} in ${channelId}`);
309
+ }
310
+ if (files.length > 1) {
311
+ const candidates = files
312
+ .map((file) => `${file.id || "unknown id"} (${file.name || file.title || "untitled"})`)
313
+ .join(", ");
314
+ throw new Error(
315
+ `message ${timestamp} has ${files.length} files; pass a file ID or file permalink to choose one: ${candidates}`
316
+ );
317
+ }
318
+ return files[0];
319
+ }
320
+ const nextCursor = response.response_metadata?.next_cursor;
321
+ if (!nextCursor || seenCursors.has(nextCursor)) {
322
+ break;
323
+ }
324
+ if (pages >= maxThreadPages) {
325
+ throw new Error(
326
+ `message ${timestamp} is beyond the first ${maxThreadPages * threadPageSize} messages of thread ${rootTs} in ${channelId}; pass a Slack file ID or file permalink to choose the attachment directly`
327
+ );
328
+ }
329
+ seenCursors.add(nextCursor);
330
+ cursor = nextCursor;
331
+ }
332
+ throw new Error(`message ${timestamp} not found in thread ${rootTs} in ${channelId}`);
333
+ };
334
+
335
+ // Writes the attachment exactly as Slack stores it: the response body is
336
+ // streamed to a temporary file beside the destination and renamed into
337
+ // place, so binary formats such as SVG are never decoded, large attachments
338
+ // are not buffered in memory, and a failed download leaves no partial file.
339
+ const saveSlackFile = async ({ reference, destinationPath }) => {
340
+ const target = parseFileReference(reference);
341
+ const file = target.message ? await resolveMessageFile(target.message) : { id: target.fileId };
342
+ const fileData = await getSlackFileData(file);
343
+ const downloadUrl = fileData.url_private_download || fileData.url_private;
344
+ if (!downloadUrl) {
345
+ throw new Error("Slack did not provide a private download URL for this file");
346
+ }
347
+ const filename = safeFilename(fileData.name || fileData.title || fileData.id);
348
+ const destination = resolveDestinationPath(destinationPath, filename);
349
+ const response = await fetch(downloadUrl, { headers: slackHeaders() });
350
+ if (!response.ok) {
351
+ throw new Error(`Slack file download failed: ${response.status}`);
352
+ }
353
+ const mimeType = (response.headers.get("content-type") || fileData.mimetype || "application/octet-stream")
354
+ .split(";", 1)[0]
355
+ .trim();
356
+ await writeResponseToFile(response, destination.path, { replaceExisting: destination.replaceExisting });
357
+ return { path: destination.path, filename: path.basename(destination.path), mimeType };
358
+ };
359
+
233
360
  const uploadSlackFiles = async ({ filePaths, channelId, threadTs, initialComment }) => {
234
361
  const localFiles = filePaths.map((filePath) => {
235
362
  const fileStats = fs.statSync(filePath);
@@ -346,7 +473,7 @@ function createSlackClient({ xoxcToken, xoxdToken, userAgent = "Mozilla/5.0" })
346
473
  return content;
347
474
  };
348
475
 
349
- return { slackApi, formatMessages, uploadSlackFiles };
476
+ return { slackApi, formatMessages, uploadSlackFiles, saveSlackFile };
350
477
  }
351
478
 
352
479
  function parsePermalink(url) {
@@ -354,7 +481,13 @@ function parsePermalink(url) {
354
481
  if (!match) {
355
482
  throw new Error("invalid Slack permalink");
356
483
  }
357
- return { channelId: match[1], timestamp: `${match[2]}.${match[3]}` };
484
+ const parsed = { channelId: match[1], timestamp: `${match[2]}.${match[3]}` };
485
+ // Reply permalinks carry the thread's parent timestamp in the query string.
486
+ const threadTs = url.match(/[?&]thread_ts=(\d+\.\d+)/)?.[1];
487
+ if (threadTs) {
488
+ parsed.threadTs = threadTs;
489
+ }
490
+ return parsed;
358
491
  }
359
492
 
360
493
  function requireString(value, name) {
@@ -364,6 +497,189 @@ function requireString(value, name) {
364
497
  return value.trim();
365
498
  }
366
499
 
500
+ // Streams a Slack download into a temporary file beside the destination and
501
+ // moves it into place, so a failed transfer never leaves a partial attachment
502
+ // and a large file never has to fit in memory.
503
+ async function writeResponseToFile(response, destinationPath, { replaceExisting = false } = {}) {
504
+ if (!response.body) {
505
+ throw new Error("Slack returned an empty file response");
506
+ }
507
+ const target = replaceExisting ? resolveSymlinkTarget(destinationPath) : destinationPath;
508
+ const tempPath = path.join(path.dirname(target), `.slack-save-${randomUUID()}.part`);
509
+ try {
510
+ await pipeline(Readable.fromWeb(response.body), fs.createWriteStream(tempPath, { flags: "wx" }));
511
+ } catch (error) {
512
+ fs.rmSync(tempPath, { force: true });
513
+ throw new Error(`could not save Slack file: ${error.message}`);
514
+ }
515
+ try {
516
+ if (replaceExisting) {
517
+ // Replacing is allowed only for a path the caller named, and a
518
+ // symlink there means write the target rather than remove the link.
519
+ // Renaming creates a new inode, so carry the replaced file's mode
520
+ // over; ownership, ACLs, and xattrs are not preserved.
521
+ const mode = existingFileMode(target);
522
+ if (mode !== undefined) {
523
+ fs.chmodSync(tempPath, mode);
524
+ }
525
+ fs.renameSync(tempPath, target);
526
+ } else {
527
+ placeWithoutReplacing(tempPath, destinationPath);
528
+ }
529
+ } catch (error) {
530
+ fs.rmSync(tempPath, { force: true });
531
+ throw error;
532
+ }
533
+ }
534
+
535
+ // Links the finished temp file into place instead of renaming it, because link
536
+ // fails with EEXIST when the destination appeared while the download ran.
537
+ // Filesystems without hard-link support fall back to a checked rename.
538
+ function placeWithoutReplacing(tempPath, destinationPath) {
539
+ try {
540
+ fs.linkSync(tempPath, destinationPath);
541
+ } catch (error) {
542
+ if (error.code === "EEXIST" || fs.existsSync(destinationPath)) {
543
+ throw new Error(`destination file already exists: ${destinationPath}; pass an explicit file path to overwrite it`);
544
+ }
545
+ fs.renameSync(tempPath, destinationPath);
546
+ return;
547
+ }
548
+ try {
549
+ fs.rmSync(tempPath, { force: true });
550
+ } catch {
551
+ // The destination link is in place; a leftover temp file is harmless.
552
+ }
553
+ }
554
+
555
+ // Follows a chain of symlinks so a save through a link writes the link's
556
+ // target, including a target that does not exist yet. The returned path shares
557
+ // a directory with the temp file, so cross-volume links are not renamed across
558
+ // filesystems.
559
+ function resolveSymlinkTarget(destinationPath) {
560
+ let current = destinationPath;
561
+ const seen = new Set();
562
+ for (;;) {
563
+ let stats;
564
+ try {
565
+ stats = fs.lstatSync(current);
566
+ } catch (error) {
567
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") {
568
+ return current;
569
+ }
570
+ throw new Error(`could not access ${current}: ${error.code || error.message}`);
571
+ }
572
+ if (!stats.isSymbolicLink()) {
573
+ return current;
574
+ }
575
+ if (seen.has(current)) {
576
+ throw new Error(`could not resolve symlink ${destinationPath}: link loop`);
577
+ }
578
+ seen.add(current);
579
+ let linkTarget;
580
+ try {
581
+ linkTarget = fs.readlinkSync(current);
582
+ } catch (error) {
583
+ throw new Error(`could not access ${current}: ${error.code || error.message}`);
584
+ }
585
+ current = path.resolve(path.dirname(current), linkTarget);
586
+ }
587
+ }
588
+
589
+ // Returns the mode of an existing regular file so a replacement keeps it, or
590
+ // undefined for a path that does not exist (or is not a file).
591
+ function existingFileMode(filePath) {
592
+ try {
593
+ const stats = fs.statSync(filePath);
594
+ return stats.isFile() ? stats.mode & 0o777 : undefined;
595
+ } catch (error) {
596
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") {
597
+ return undefined;
598
+ }
599
+ throw error;
600
+ }
601
+ }
602
+
603
+ const WINDOWS_RESERVED_NAME = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\..*)?$/i;
604
+
605
+ // A saved attachment keeps the name Slack reports, but a path separator must
606
+ // not let the name escape the destination directory, and Windows interprets
607
+ // names such as "Q3: plan.pdf" as an alternate data stream on "Q3" while
608
+ // reserved device names are unusable as files. Such characters are replaced on
609
+ // Windows; other platforms keep the original name.
610
+ function safeFilename(name, platform = process.platform) {
611
+ let value = String(name ?? "").trim().replace(/[\\/]+/g, "_");
612
+ if (platform === "win32") {
613
+ value = value.replace(/[<>:"|?*\u0000-\u001f]/g, "_").replace(/[. ]+$/, "");
614
+ if (WINDOWS_RESERVED_NAME.test(value)) {
615
+ value = `_${value}`;
616
+ }
617
+ }
618
+ return value && value !== "." && value !== ".." ? value : "slack-file";
619
+ }
620
+
621
+ function statDestinationPath(candidate) {
622
+ try {
623
+ return fs.statSync(candidate);
624
+ } catch (error) {
625
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") {
626
+ return undefined;
627
+ }
628
+ throw new Error(`could not access ${candidate}: ${error.code || error.message}`);
629
+ }
630
+ }
631
+
632
+ // Resolves a destination that is either an existing directory (keep Slack's
633
+ // filename, refusing to replace a file already there) or the full path of the
634
+ // file to write. The parent directory must already exist, so a typo fails
635
+ // before the attachment is downloaded.
636
+ function resolveDestinationPath(destinationPath, filename) {
637
+ const value = requireString(destinationPath, "destination_path");
638
+ const resolved = path.resolve(expandHome(value));
639
+ const stats = statDestinationPath(resolved);
640
+ if (stats?.isDirectory()) {
641
+ const target = path.join(resolved, filename);
642
+ if (fs.existsSync(target)) {
643
+ throw new Error(`destination file already exists: ${target}; pass an explicit file path to overwrite it`);
644
+ }
645
+ return { path: target, replaceExisting: false };
646
+ }
647
+ if (stats && !stats.isFile()) {
648
+ throw new Error(`destination is not a regular file or directory: ${resolved}`);
649
+ }
650
+ if (!stats && /[\\/]$/.test(value)) {
651
+ throw new Error(`destination directory does not exist: ${resolved}`);
652
+ }
653
+ const directory = path.dirname(resolved);
654
+ const directoryStats = statDestinationPath(directory);
655
+ if (!directoryStats) {
656
+ throw new Error(`destination directory does not exist: ${directory}`);
657
+ }
658
+ if (!directoryStats.isDirectory()) {
659
+ throw new Error(`destination parent is not a directory: ${directory}`);
660
+ }
661
+ return { path: resolved, replaceExisting: true };
662
+ }
663
+
664
+ // Accepts a Slack file ID (F…), a file permalink (/files/F…), or a message
665
+ // permalink (/archives/C…/p…). Anything else is rejected rather than guessed.
666
+ function parseFileReference(reference) {
667
+ const value = requireString(reference, "file");
668
+ const filePermalink = value.match(/\/files\/(?:[A-Z0-9]+\/)?(F[A-Z0-9]+)/i);
669
+ if (filePermalink) {
670
+ return { fileId: filePermalink[1].toUpperCase() };
671
+ }
672
+ if (/^F[A-Z0-9]+$/i.test(value)) {
673
+ return { fileId: value.toUpperCase() };
674
+ }
675
+ if (value.includes("/archives/")) {
676
+ return { message: parsePermalink(value) };
677
+ }
678
+ throw new Error(
679
+ `invalid Slack file reference: ${value} (expected a Slack permalink or a file ID such as F0123ABCD)`
680
+ );
681
+ }
682
+
367
683
  function assertAllowedWriteChannel(channelId, allowed) {
368
684
  if (!allowed.has(channelId)) {
369
685
  throw new Error(`writes are not allowed for channel ${channelId}`);
@@ -395,7 +711,9 @@ function withAgentPrefix(text, model) {
395
711
  const AgentModelField = z
396
712
  .string()
397
713
  .optional()
398
- .describe("Model you are running, e.g. gpt-5.1, shown in the 🤖 prefix. Omit when unknown.");
714
+ .describe(
715
+ "Backend model ID you are running, for example claude-sonnet-4-5, not a display name; shown in the 🤖 prefix. Always pass it on an agent-authored post, and omit it only when your client cannot determine its model ID."
716
+ );
399
717
 
400
718
  const ReadPermalinkSchema = z.object({
401
719
  url: z.string().describe("Slack permalink, e.g. https://<workspace>.slack.com/archives/C.../p..."),
@@ -433,6 +751,19 @@ const UploadFilesSchema = z.object({
433
751
  model: AgentModelField,
434
752
  });
435
753
 
754
+ const SaveFileSchema = z.object({
755
+ file: z
756
+ .string()
757
+ .min(1)
758
+ .describe("Slack permalink for the message or file, or a Slack file ID such as F0123ABCD."),
759
+ destination_path: z
760
+ .string()
761
+ .min(1)
762
+ .describe(
763
+ "Local file path to write, or an existing directory that keeps the attachment's filename. An existing directory refuses to replace a file already there; pass an explicit file path to overwrite."
764
+ ),
765
+ });
766
+
436
767
  const EditMessageSchema = z.object({
437
768
  channel_id: z.string(),
438
769
  timestamp: z.string().describe("Timestamp of the message or thread reply to edit."),
@@ -465,7 +796,7 @@ const TOOLS = [
465
796
  },
466
797
  {
467
798
  name: "slack_reply_to_thread",
468
- description: "Reply to a Slack thread. The posted text is prefixed with `🤖:` — or `🤖 <model>:` when model is given — so readers can tell it came from an agent; pass model to name the model writing it. Restricted to allowed channels.",
799
+ description: "Reply to a Slack thread. The posted text is prefixed with `🤖:` — or `🤖 <model>:` when model is given — so readers can tell it came from an agent; always pass model with the backend model ID you are running when you know it, and omit it only when you cannot determine it. Restricted to allowed channels.",
469
800
  inputSchema: zodToJsonSchema(ReplyToThreadSchema),
470
801
  },
471
802
  {
@@ -480,19 +811,25 @@ const TOOLS = [
480
811
  },
481
812
  {
482
813
  name: "slack_upload_files",
483
- description: "Upload one or more local files to a channel or thread. A given initial_comment is prefixed with `🤖:` — or `🤖 <model>:` when model is given — so readers can tell it came from an agent; pass model to name the model writing it, and note that model has no effect without initial_comment. Restricted to allowed channels.",
814
+ description: "Upload one or more local files to a channel or thread. A given initial_comment is prefixed with `🤖:` — or `🤖 <model>:` when model is given — so readers can tell it came from an agent; always pass model with the backend model ID you are running when you know it (it has no effect without initial_comment), and omit it only when you cannot determine it. Restricted to allowed channels.",
484
815
  inputSchema: zodToJsonSchema(UploadFilesSchema),
485
816
  },
817
+ {
818
+ name: "slack_save_file",
819
+ description:
820
+ "Save a file attached to a Slack message to a local path, keeping the original bytes. Accepts a message or file permalink, or a file ID. Returns the saved path, filename, and MIME type. The destination's parent directory must exist; an existing directory keeps the attachment's filename, with characters the local filesystem rejects replaced, and refuses to overwrite an existing file.",
821
+ inputSchema: zodToJsonSchema(SaveFileSchema),
822
+ },
486
823
  {
487
824
  name: "slack_edit_message",
488
- description: "Edit an authored Slack message or thread reply by channel id and timestamp. Replaces the message text, prefixed with `🤖:` — or `🤖 <model>:` when model is given — unless it already carries the prefix; pass model to name the model writing it, and set agent_authored to false when the new text is not agent-written. Any existing Block Kit blocks are removed by Slack. Restricted to allowed channels.",
825
+ description: "Edit an authored Slack message or thread reply by channel id and timestamp. Replaces the message text, prefixed with `🤖:` — or `🤖 <model>:` when model is given — unless it already carries the prefix; always pass model with the backend model ID you are running when you know it, and omit it only when you cannot determine it. Set agent_authored to false when the new text is not agent-written. Any existing Block Kit blocks are removed by Slack. Restricted to allowed channels.",
489
826
  inputSchema: zodToJsonSchema(EditMessageSchema),
490
827
  },
491
828
  ];
492
829
 
493
830
  // ── Execute factory (exported for tests) ─────────────────────────────────────
494
831
 
495
- function createExecuteToolCall({ slackApi, formatMessages, uploadSlackFiles, allowedWriteChannels }) {
832
+ function createExecuteToolCall({ slackApi, formatMessages, uploadSlackFiles, saveSlackFile, allowedWriteChannels }) {
496
833
  const allowed = new Set(allowedWriteChannels);
497
834
  return async function executeToolCall(name, args) {
498
835
  switch (name) {
@@ -580,6 +917,22 @@ function createExecuteToolCall({ slackApi, formatMessages, uploadSlackFiles, all
580
917
  };
581
918
  }
582
919
 
920
+ case "slack_save_file": {
921
+ const a = SaveFileSchema.parse(args);
922
+ const saved = await saveSlackFile({
923
+ reference: requireString(a.file, "file"),
924
+ destinationPath: requireString(a.destination_path, "destination_path"),
925
+ });
926
+ return {
927
+ content: [
928
+ {
929
+ type: "text",
930
+ text: `saved file: ${saved.path}\nfilename: ${saved.filename}\nmime type: ${saved.mimeType}`,
931
+ },
932
+ ],
933
+ };
934
+ }
935
+
583
936
  case "slack_edit_message": {
584
937
  const a = EditMessageSchema.parse(args);
585
938
  const channelId = requireString(a.channel_id, "channel_id");
@@ -625,6 +978,11 @@ function createExecuteToolCall({ slackApi, formatMessages, uploadSlackFiles, all
625
978
  // ── Main ─────────────────────────────────────────────────────────────────────
626
979
 
627
980
  async function main() {
981
+ const legacyDiagnostic = legacyEnvDiagnostic();
982
+ if (legacyDiagnostic) {
983
+ console.error(legacyDiagnostic);
984
+ }
985
+
628
986
  let config;
629
987
  try {
630
988
  config = loadConfig();
@@ -642,14 +1000,14 @@ async function main() {
642
1000
  process.exit(1);
643
1001
  }
644
1002
 
645
- const { slackApi, formatMessages, uploadSlackFiles } = createSlackClient({ xoxcToken, xoxdToken, userAgent: config.userAgent });
1003
+ const { slackApi, formatMessages, uploadSlackFiles, saveSlackFile } = createSlackClient({ xoxcToken, xoxdToken, userAgent: config.userAgent });
646
1004
 
647
1005
  const server = new Server(
648
- { name: "yt-slack-mcp", version: "0.1.0" },
1006
+ SERVER_INFO,
649
1007
  {
650
1008
  capabilities: { tools: {} },
651
1009
  instructions:
652
- "MCP server for Slack. Read with slack_read_permalink, slack_get_replies, slack_get_history; write with slack_reply_to_thread, slack_add_reaction, slack_remove_reaction, slack_upload_files, slack_edit_message (restricted to allowed channels). Messages sent by the write tools are prefixed with `🤖:` by default, and slack_edit_message can opt out with agent_authored false; pass model with the model you are running to include it in the prefix.",
1010
+ "MCP server for Slack. Read with slack_read_permalink, slack_get_replies, slack_get_history; save an attachment with slack_save_file; write with slack_reply_to_thread, slack_add_reaction, slack_remove_reaction, slack_upload_files, slack_edit_message (restricted to allowed channels). Messages sent by the write tools are prefixed with `🤖:` by default, and slack_edit_message can opt out with agent_authored false; always pass model with the backend model ID you are running when you know it, for example claude-sonnet-4-5, so the prefix names the model — omit it only when you cannot determine it.",
653
1011
  }
654
1012
  );
655
1013
 
@@ -659,6 +1017,7 @@ async function main() {
659
1017
  slackApi,
660
1018
  formatMessages,
661
1019
  uploadSlackFiles,
1020
+ saveSlackFile,
662
1021
  allowedWriteChannels: config.allowedWriteChannels,
663
1022
  });
664
1023
 
@@ -691,6 +1050,8 @@ if (isMain) {
691
1050
 
692
1051
  export {
693
1052
  TOOLS,
1053
+ SERVER_INFO,
1054
+ parseChannelList,
694
1055
  parsePermalink,
695
1056
  requireString,
696
1057
  assertAllowedWriteChannel,
@@ -698,13 +1059,17 @@ export {
698
1059
  createExecuteToolCall,
699
1060
  createSlackClient,
700
1061
  loadConfig,
1062
+ legacyEnvDiagnostic,
701
1063
  expandHome,
702
- parseChannelList,
1064
+ parseFileReference,
1065
+ safeFilename,
1066
+ resolveDestinationPath,
703
1067
  ReadPermalinkSchema,
704
1068
  GetRepliesSchema,
705
1069
  GetHistorySchema,
706
1070
  ReplyToThreadSchema,
707
1071
  AddReactionSchema,
708
1072
  UploadFilesSchema,
1073
+ SaveFileSchema,
709
1074
  EditMessageSchema,
710
1075
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "yt-slack-mcp",
3
- "version": "0.5.0",
4
- "description": "MCP server for Slack — read permalinks, threads, and channel history; reply to threads; add or remove reactions; edit messages.",
3
+ "version": "0.7.0",
4
+ "description": "MCP server for Slack — read permalinks, threads, and channel history; save attachments to local paths; reply to threads; add or remove reactions; edit messages.",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "bin": {
@@ -11,7 +11,8 @@
11
11
  "test": "node --test --experimental-test-coverage"
12
12
  },
13
13
  "files": [
14
- "index.js"
14
+ "index.js",
15
+ "skills/*/SKILL.md"
15
16
  ],
16
17
  "keywords": [
17
18
  "mcp",
@@ -0,0 +1,151 @@
1
+ ---
2
+ name: slack-mcp
3
+ description: Read and write Slack through yt-slack-mcp — read permalinks, threads, channel history, and attachments; save an attachment to a local file; reply in threads, react, upload files, and edit messages in allowed channels. Use when asked to inspect a Slack link, summarize a channel or thread, find recent channel messages, save an attachment, or reply, react, upload, or edit in Slack.
4
+ ---
5
+
6
+ # Slack MCP
7
+
8
+ Use the `yt-slack-mcp` MCP server through this skill. Read before writing, and
9
+ write only where the channel allow-list permits.
10
+
11
+ Server: `yt-slack-mcp` 0.7.0, launched as `npx yt-slack-mcp` over stdio.
12
+
13
+ ## Setup and auth
14
+
15
+ The server talks to Slack through your logged-in browser session, not a bot
16
+ token.
17
+
18
+ 1. Save the `xoxc` token (Slack web localStorage) as a single line in
19
+ `~/.config/yt-slack-mcp/secrets/slack-xoxc.txt`.
20
+ 2. Save the `xoxd` token (the cookie named `d`) as a single line in
21
+ `~/.config/yt-slack-mcp/secrets/slack-xoxd.txt`.
22
+ 3. Allow writes by listing channel IDs in `allowedWriteChannels` in
23
+ `~/.config/yt-slack-mcp/config.json`. With an empty or missing list, every
24
+ write is refused.
25
+
26
+ Configuration is file-based: `config.json` also accepts `secretsDir`, `xoxcPath`,
27
+ `xoxdPath`, and `userAgent`, and the defaults apply when a key is absent. Never
28
+ echo a token or a file's contents back to the user.
29
+
30
+ ### What each failure means
31
+
32
+ | Message | Cause | Fix |
33
+ |---------|-------|-----|
34
+ | `Error: missing slack-xoxc.txt (looked at <path>)` | The `xoxc` file is absent at startup; the server exits before listing tools. | Write the token file at the reported path, or set `xoxcPath` in `config.json` to point at it. |
35
+ | `Error: missing slack-xoxd.txt (looked at <path>)` | Same, for the `xoxd` file. | Write the token file at the reported path, or set `xoxdPath` in `config.json` to point at it. |
36
+ | `Error: invalid Slack MCP config <path>: <detail>` | `config.json` is not valid JSON, or a value has the wrong type; the detail names the problem. | Fix the JSON, correct the value, or remove the file. |
37
+ | `Error: writes are not allowed for channel <id>` | The channel is not in the allow-list. | Add the channel ID to the allow-list if the user wants writes there; never work around the refusal. |
38
+ | `slack <method> failed: invalid_auth` (or `not_authed`) | The browser session expired or the token was copied incorrectly. | Refresh the `xoxc`/`xoxd` pair, then retry once. |
39
+ | `Error: missing <name>` | A required write-tool argument (`channel_id`, `thread_ts`, `timestamp`, `text`, `reaction`) was blank. | Supply the actual value; do not invent IDs. |
40
+
41
+ Tool errors arrive as text starting with `Error:`. Report the text instead of
42
+ retrying the same call unchanged.
43
+
44
+ ## Troubleshooting
45
+
46
+ - **Writes refused or tokens missing after an upgrade.** Configuration is
47
+ file-based only: values supplied through environment variables are ignored.
48
+ Move `secretsDir`, `xoxcPath`, `xoxdPath`, `allowedWriteChannels`, and
49
+ `userAgent` into `~/.config/yt-slack-mcp/config.json`.
50
+ - **Only some expected channels are writable.** `allowedWriteChannels` is the
51
+ complete list with no additive default; compare it with the channel IDs the
52
+ user expects.
53
+ - **The server exits at startup.** A reported token path is missing; create the
54
+ file at that path. An empty or stale token does not stop startup; the first
55
+ Slack call fails later as `invalid_auth`.
56
+ - **A write still fails inside an allowed channel.** The browser session may have
57
+ lost write access or the message may be outside the edit window; report the
58
+ exact `Error:` text instead of retrying.
59
+
60
+ ## Tool map
61
+
62
+ Choose the read tool from what the user gave you, and the write tool from the
63
+ action they asked for.
64
+
65
+ | Tool | Use it when |
66
+ |------|-------------|
67
+ | `slack_read_permalink` | A Slack link is the input. Reads the linked message's thread, including inline images, PDF text, and text attachments. |
68
+ | `slack_save_file` | The user needs an attachment on disk. Accepts a message or file permalink, or a file ID, plus `destination_path`; keeps the original bytes, replaces characters the OS rejects in the filename, and refuses to overwrite an existing file in a directory destination. Reports the saved path, filename, and MIME type. It is not channel-restricted. |
69
+ | `slack_get_replies` | You have a channel ID and thread timestamp and need that thread again or its latest replies. |
70
+ | `slack_get_history` | There is no link or thread: read recent messages when you have a channel ID. The tool does not resolve channel names. |
71
+ | `slack_reply_to_thread` | Post a reply into an existing thread. Requires `channel_id`, `thread_ts`, `text`, and `model` set to your backend model ID whenever you can determine it. |
72
+ | `slack_add_reaction` | Mark or acknowledge a message without posting text. |
73
+ | `slack_remove_reaction` | Remove a reaction this account added. |
74
+ | `slack_upload_files` | Post up to 10 local files (10 MB each) to a channel or thread, with an optional `initial_comment`. |
75
+ | `slack_edit_message` | Correct a message this account already posted, by channel ID and timestamp. |
76
+
77
+ The server has no plain top-level text post; a reply needs an existing thread.
78
+ A file upload with an `initial_comment` is the only way to start a new top-level
79
+ message. Say so instead of promising a text post.
80
+
81
+ ## Recipes
82
+
83
+ ### Read a permalink and reply in its thread
84
+
85
+ 1. Call `slack_read_permalink` with the `url`.
86
+ 2. Take the channel ID from the permalink and the root `[ts]` from the first
87
+ returned message.
88
+ 3. Read the whole thread before answering; do not repost what is already there.
89
+ 4. Call `slack_reply_to_thread` with `channel_id`, `thread_ts`, `text`, and
90
+ `model` set to the backend model ID you are running, for example
91
+ `claude-sonnet-4-5` — not a display name.
92
+
93
+ ### Summarize a channel
94
+
95
+ 1. Resolve the channel ID first. The tool does not accept names like `#ops`; take
96
+ the ID from a permalink or ask the user.
97
+ 2. Call `slack_get_history` with `channel_id` and `limit` up to 200.
98
+ 3. Summarize in the conversation, quoting `[ts]` values when the user needs to
99
+ locate a message.
100
+ 4. Post the summary only when asked, and only as a reply in a relevant thread or
101
+ as a file upload's `initial_comment`; there is no plain top-level text post.
102
+
103
+ ### Upload a file with a comment
104
+
105
+ 1. Resolve absolute local paths; at most 10 files, 10 MB each.
106
+ 2. Call `slack_upload_files` with `file_paths`, `channel_id`, an optional
107
+ `thread_ts`, and `initial_comment` when a message should accompany the files.
108
+ 3. Pass `model` with the backend model ID you are running; it is used only when
109
+ `initial_comment` is present, and without a comment the upload stays
110
+ comment-free.
111
+ 4. Report the returned file and message permalinks.
112
+
113
+ ### Save an attachment to disk
114
+
115
+ 1. Take the message or file permalink, or the file ID, from the user.
116
+ 2. Resolve the destination: an existing directory keeps Slack's filename, with
117
+ characters the OS rejects replaced, and refuses to overwrite a file already
118
+ there; pass an explicit file path to overwrite. Its parent directory must
119
+ exist.
120
+ 3. Call `slack_save_file` with `file` and `destination_path`.
121
+ 4. Report the returned saved path, filename, and MIME type. If the message has
122
+ several attachments, the error lists their IDs; retry with the one the user
123
+ meant.
124
+
125
+ ### Correct a posted message
126
+
127
+ 1. Call `slack_edit_message` with `channel_id`, the message `timestamp`, and the
128
+ replacement `text`.
129
+ 2. Leave `agent_authored` at its default for agent-written text; pass `model`
130
+ with your backend model ID so the prefix names the model.
131
+ 3. Pass `agent_authored: false` only when replacing agent text with the user's own
132
+ words, such as correcting their message; `model` is then ignored.
133
+ 4. Slack removes existing Block Kit blocks on edit and only allows edits to this
134
+ account's messages within its edit window.
135
+
136
+ ## Guardrails
137
+
138
+ - Read before writing. Fetch the thread or channel context first, even when the
139
+ requested text seems obvious.
140
+ - Stay inside the allow-list. Never attempt a write to a channel that is not
141
+ listed, and never suggest disabling the check to "make it work".
142
+ - Always pass `model` on every text-writing call — reply, upload with a comment,
143
+ edit — with the backend model ID you are running, for example
144
+ `claude-sonnet-4-5`, not a display name, so posts read `🤖 <model ID>:`. Omit it
145
+ only when you cannot determine your model ID. Never add the prefix yourself;
146
+ the server adds it once.
147
+ - `agent_authored: false` is an explicit correction of non-agent text, not a
148
+ default and not a way to hide that an agent posted.
149
+ - Channel names are not resolved. Never pass `#name` as `channel_id`; use a
150
+ `C...`, `G...`, or `D...` ID from a permalink or ask the user.
151
+ - Prefer edits over reposting. Do not "fix" a message by posting it again.