@orygn/discord-mcp 2.0.0-rc.0 → 2.1.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.
Files changed (51) hide show
  1. package/LICENSE +202 -202
  2. package/README.md +396 -353
  3. package/dist/builder/executor.js +1 -1
  4. package/dist/builder/overwrites.js +2 -2
  5. package/dist/builder/planner.js +2 -2
  6. package/dist/config.js +17 -5
  7. package/dist/discord/client.js +16 -8
  8. package/dist/discord/gateway.js +5 -8
  9. package/dist/discord/gatewayEvents.js +1 -2
  10. package/dist/discord/grants.js +2 -2
  11. package/dist/discord/guildData.js +2 -3
  12. package/dist/discord/images.js +2 -2
  13. package/dist/discord/messageImages.js +2 -2
  14. package/dist/discord/rateLimit.js +1 -3
  15. package/dist/http.js +3 -3
  16. package/dist/index.js +7 -0
  17. package/dist/install.js +7 -8
  18. package/dist/instructions.js +27 -4
  19. package/dist/lifecycle.js +15 -5
  20. package/dist/packaging.js +11 -0
  21. package/dist/restrictions.js +57 -0
  22. package/dist/safety.js +77 -32
  23. package/dist/scheduler.js +17 -9
  24. package/dist/server.js +114 -32
  25. package/dist/settings.js +3 -0
  26. package/dist/textFiles.js +8 -0
  27. package/dist/tools/appCommands.js +11 -4
  28. package/dist/tools/automod.js +1 -2
  29. package/dist/tools/botProfile.js +6 -0
  30. package/dist/tools/catchUp.js +2 -2
  31. package/dist/tools/common.js +33 -18
  32. package/dist/tools/community.js +4 -4
  33. package/dist/tools/diagnostics.js +47 -22
  34. package/dist/tools/forums.js +4 -4
  35. package/dist/tools/manage.js +2 -2
  36. package/dist/tools/messaging.js +153 -30
  37. package/dist/tools/moderation.js +4 -4
  38. package/dist/tools/permissions.js +3 -3
  39. package/dist/tools/reactions.js +2 -3
  40. package/dist/tools/read.js +1 -3
  41. package/dist/tools/realtime.js +1 -1
  42. package/dist/tools/roster.js +12 -3
  43. package/dist/tools/settings.js +2 -2
  44. package/dist/tools/write.js +2 -2
  45. package/dist/unknownArguments.js +8 -7
  46. package/dist/updateCheck.js +19 -4
  47. package/dist/usageReport.js +421 -0
  48. package/dist/usageStats.js +253 -0
  49. package/dist/wizard.js +23 -3
  50. package/dist/wizardLib.js +32 -11
  51. package/package.json +70 -70
@@ -39,8 +39,8 @@ export class ToolProblem extends Error {
39
39
  }
40
40
  // Network failures below the API layer (connection timeouts, resets, DNS
41
41
  // trouble) are transient and worth a retry; surfacing them as raw stack
42
- // noise leaves the model guessing. Observed live during a flaky-network
43
- // Desktop session as undici ConnectTimeoutErrors.
42
+ // noise leaves the model guessing. They arrive as undici
43
+ // ConnectTimeoutErrors, among others.
44
44
  function isNetworkError(err) {
45
45
  if (!(err instanceof Error))
46
46
  return false;
@@ -64,9 +64,8 @@ function isNetworkError(err) {
64
64
  return /connect timeout|fetch failed/i.test(err.message);
65
65
  }
66
66
  // The public archived threads of a channel, newest first. Discord hands
67
- // them out a page at a time and says whether more remain; the first page
68
- // used to be reported as all of them. Read up to a cap, with "more" saying
69
- // whether older ones were left out.
67
+ // them out a page at a time and says whether more remain. Read up to a cap,
68
+ // with "more" saying whether older ones were left out.
70
69
  export async function archivedThreads(rest, channelId, cap = 300) {
71
70
  const threads = [];
72
71
  let before;
@@ -236,12 +235,16 @@ export async function enter(config, guildArg, botArg, opts = {}) {
236
235
  return { name: b.name, guilds: [] };
237
236
  }
238
237
  }));
238
+ // DISCORD_MCP_ALLOWED_SERVERS: a server outside the list does not exist as
239
+ // far as the tools are concerned, whether it is named, given by id, or
240
+ // reached through a message link.
241
+ const visible = allowedGuildsOnly(botGuilds, config.allowedServers);
239
242
  const defaultBot = config.bots.find((b) => b.isDefault)?.name;
240
243
  const prefer = { defaultBot, byServer: config.serverBots };
241
- let resolution = resolveBotGuild(botGuilds, wanted, opts.shared === "ask" ? {} : opts.shared === "listening" ? { defaultBot } : prefer);
244
+ let resolution = resolveBotGuild(visible, wanted, opts.shared === "ask" ? {} : opts.shared === "listening" ? { defaultBot } : prefer);
242
245
  const heard = opts.shared === "listening" && resolution.kind === "match" && resolution.botName === defaultBot;
243
246
  if (opts.shared === "listening" && resolution.kind === "ambiguous-bot") {
244
- resolution = resolveBotGuild(botGuilds, wanted, prefer);
247
+ resolution = resolveBotGuild(visible, wanted, prefer);
245
248
  }
246
249
  switch (resolution.kind) {
247
250
  case "match": {
@@ -261,8 +264,7 @@ export async function enter(config, guildArg, botArg, opts = {}) {
261
264
  throw new ToolProblem(fail(`Internal error resolving bot "${resolution.botName}".`));
262
265
  }
263
266
  // Record the acting bot for the safety gate, but only when more than one
264
- // bot is configured. With a single bot there is nothing to disambiguate,
265
- // so single-bot previews and tokens stay exactly as before.
267
+ // bot is configured. With a single bot there is nothing to disambiguate.
266
268
  if (config.bots.length > 1) {
267
269
  setActingBot({ bot: bot.name, server: resolution.guildName });
268
270
  }
@@ -284,13 +286,28 @@ export async function enter(config, guildArg, botArg, opts = {}) {
284
286
  server: { id: resolution.guildId, name: resolution.guildName },
285
287
  bots: resolution.bots,
286
288
  }));
287
- case "no-guild":
289
+ case "no-guild": {
290
+ // Said plainly when the server exists but is not allowed here, so
291
+ // nobody goes looking for a missing invite.
292
+ const outside = config.allowedServers ? resolveBotGuild(botGuilds, wanted, {}) : undefined;
293
+ if (outside && (outside.kind === "match" || outside.kind === "ambiguous-bot")) {
294
+ throw new ToolProblem(fail(`${quoted(outside.guildName)} is not one of the servers this install may act in ` +
295
+ `(${settingSource("ALLOWED_SERVERS")}). Nothing was done there.`));
296
+ }
288
297
  throw new ToolProblem(fail(`No configured bot is in a server matching "${wanted}". ` +
289
298
  "Check the name, or invite one of your bots to that server first."));
299
+ }
290
300
  case "ambiguous-guild":
291
301
  throw new ToolProblem(fail(`More than one server matches "${wanted}". Use an exact name or ID.`, { candidates: resolution.candidates }));
292
302
  }
293
303
  }
304
+ // Each bot's server list narrowed to the allowed servers, or as it is when
305
+ // no list is set. Pure, for the unit suite.
306
+ export function allowedGuildsOnly(botGuilds, allowed) {
307
+ if (!allowed)
308
+ return botGuilds;
309
+ return botGuilds.map((b) => ({ ...b, guilds: b.guilds.filter((g) => allowed.has(g.id)) }));
310
+ }
294
311
  // Select a bot for operations that are not tied to a server (bot identity,
295
312
  // diagnostics). Defaults to the default bot; an explicit name picks another.
296
313
  // Throws a ToolProblem when nothing is configured or the name does not resolve.
@@ -404,8 +421,8 @@ export async function resolveMember(rest, guildId, query) {
404
421
  // exactly the query could be left out behind five who merely start with it.
405
422
  const MEMBER_SEARCH_LIMIT = 25;
406
423
  // A member as the resolver sees them: found by username, display name, or
407
- // server nickname alike. Before, only the username counted, so asking for
408
- // "Sam" picked samantha_k (username) over the member everyone sees as Sam.
424
+ // server nickname alike, so asking for "Sam" finds the member everyone sees
425
+ // as Sam, not samantha_k by username.
409
426
  export function memberResolvable(m) {
410
427
  return {
411
428
  id: m.user?.id ?? "",
@@ -449,7 +466,7 @@ export function flaggedMedia(m) {
449
466
  }
450
467
  // Said wherever messages are listed: the digest names attachments only by
451
468
  // file name, and a model reading one has no way to know the picture can be
452
- // fetched for it (seen with a real model: it said it could not see one).
469
+ // fetched for it.
453
470
  export function imagesHint(messages) {
454
471
  const n = messages.filter((m) => collectImages(m).length > 0).length;
455
472
  if (n === 0)
@@ -525,7 +542,7 @@ export function digestMessage(m) {
525
542
  ...(texts.length > 0 ? { embeds_text: texts } : {}),
526
543
  ...(forwarded ? { forwarded } : {}),
527
544
  // Only present when Discord's scanning flagged something, so ordinary
528
- // messages read exactly as before.
545
+ // messages are unaffected.
529
546
  ...(flagged.length > 0 ? { flagged_media: flagged } : {}),
530
547
  reactions: (m.reactions ?? []).map((r) => ({
531
548
  emoji: r.emoji.name ?? r.emoji.id ?? "?",
@@ -618,10 +635,8 @@ export function parseHexColor(value) {
618
635
  }
619
636
  // Embed input, shared by every tool that posts or edits a message.
620
637
  //
621
- // The objects are strict: a key they do not know is refused. They used to
622
- // take a title, a body, a color, and a link and drop anything else without
623
- // a word, so a caller who passed fields got a card with none and no hint
624
- // why.
638
+ // The objects are strict: a key they do not know is refused, so a caller
639
+ // never gets a card missing what they passed with no hint why.
625
640
  const EMBED_PICTURE = /^(https?|attachment):\/\/\S+$/i;
626
641
  const pictureUrl = (name) => z
627
642
  .string()
@@ -44,7 +44,7 @@ async function inviteTargets(rest, code) {
44
44
  }
45
45
  }
46
46
  // A lifetime in the largest unit that reads cleanly. Rounding to hours
47
- // said "0 hour(s)" for a five-minute invite.
47
+ // would say "0 hour(s)" for a five-minute invite.
48
48
  export function describeDuration(seconds) {
49
49
  const unit = (n, name) => `${n} ${name}${n === 1 ? "" : "s"}`;
50
50
  if (seconds < 60)
@@ -209,8 +209,8 @@ export function registerCommunityTools(server, config) {
209
209
  // handed over. The list travels in a field Discord could stop
210
210
  // honouring, and an invite created without it is open to anyone with
211
211
  // the link, roles included, while this tool would report it as
212
- // limited. Discord applies the list at once (checked live with a
213
- // thousand people), so anything but the same list back means the
212
+ // limited. Discord applies the list at once (checked live with a list
213
+ // of a thousand), so anything but the same list back means the
214
214
  // invite is not what was asked for, and it is revoked.
215
215
  if (targets) {
216
216
  const limitedTo = await inviteTargets(rest, invite.code);
@@ -328,7 +328,7 @@ export function registerCommunityTools(server, config) {
328
328
  const clean = inviteCode(code);
329
329
  // The invite must be this server's. Discord revokes any invite the
330
330
  // bot has rights over, whichever server it belongs to, so without
331
- // this a code from another server the bot is in was revoked there
331
+ // this a code from another server the bot is in would be revoked there
332
332
  // while the confirmation named this one.
333
333
  let invite;
334
334
  try {
@@ -14,9 +14,11 @@ import { rateLimitStats } from "../discord/rateLimit.js";
14
14
  import { growthChecks } from "../discord/thresholds.js";
15
15
  import { SERVER_INFO } from "../identity.js";
16
16
  import { LEGACY_PREFIX, PREFIX, legacySettingsInUse, settingSource } from "../settings.js";
17
- import { RELEASES_URL, UPDATE_COMMAND, availableUpdate } from "../updateCheck.js";
17
+ import { RELEASES_URL, availableUpdate, updateSteps } from "../updateCheck.js";
18
18
  import { confirmMode, safeModeEnabled, unknownConfirmMode } from "../safety.js";
19
19
  import { appCanShowDialog } from "../requestContext.js";
20
+ import { usageLine } from "../usageStats.js";
21
+ import { BUNDLE_SETTINGS, packagedAs } from "../packaging.js";
20
22
  // The gateway state reported for a bot other than the default one.
21
23
  const NO_CONNECTION = { status: "off", reason: "only the default bot holds the live connection" };
22
24
  const PORTAL_BOT_PAGE = "https://discord.com/developers/applications, select your app, Bot page";
@@ -64,9 +66,8 @@ export function registerDiagnostics(server, config) {
64
66
  rest.get(Routes.userGuilds()),
65
67
  ]);
66
68
  const intents = readIntents(app.flags ?? 0);
67
- // The guild list endpoint returns at most 200 entries per page.
68
- // Pagination is not worth wiring up until a bot of ours can
69
- // realistically exceed that.
69
+ // The guild list endpoint returns at most 200 entries per page, so
70
+ // a full page is reported as "200 or more".
70
71
  const guildCount = guilds.length;
71
72
  const guildCountDisplay = guildCount >= 200 ? "200 or more" : String(guildCount);
72
73
  const intentSummary = [
@@ -74,9 +75,15 @@ export function registerDiagnostics(server, config) {
74
75
  intents.messageContent ? "message content on" : "message content OFF",
75
76
  intents.presence ? "presence on" : "presence off",
76
77
  ].join(", ");
78
+ // The id list is there to pick a server by, so it leaves out the
79
+ // ones this install may not act in. The count stays the bot's own.
80
+ const allowed = config.allowedServers;
81
+ const pickable = allowed ? guilds.filter((g) => allowed.has(g.id)) : guilds;
82
+ const settings = restrictionLines(config);
77
83
  return ok(`Logged in as ${user.username} (app: ${app.name}). ` +
78
84
  `In ${guildCountDisplay} server${guildCount === 1 ? "" : "s"}. Intents: ${intentSummary}. ` +
79
- `discord-mcp v${VERSION}.`, {
85
+ `discord-mcp v${VERSION}.` +
86
+ (settings.length > 0 ? ` ${settings.join(" ")}` : ""), {
80
87
  bot: {
81
88
  id: user.id,
82
89
  username: user.username,
@@ -90,13 +97,13 @@ export function registerDiagnostics(server, config) {
90
97
  // First few guilds by id and name. Enough for a human or a
91
98
  // model to grab the right id for DISCORD_MCP_GUILD without a
92
99
  // separate lookup.
93
- list: guilds
100
+ list: pickable
94
101
  .slice(0, 10)
95
102
  .map((g) => ({ id: g.id, name: g.name })),
96
103
  },
97
- // Only the default bot holds the live connection. Its state
98
- // was reported for every bot, so a second bot read as online
99
- // and watchable when it is neither.
104
+ ...(settings.length > 0 ? { settings } : {}),
105
+ // Only the default bot holds the live connection, so any other
106
+ // bot is reported as having none.
100
107
  gateway: selectedBot.isDefault ? getGatewayState() : NO_CONNECTION,
101
108
  intents,
102
109
  server: { name: SERVER_INFO.name, version: VERSION },
@@ -142,8 +149,7 @@ export function registerDiagnostics(server, config) {
142
149
  check: "version",
143
150
  status: "warn",
144
151
  detail: `discord-mcp ${newer} is available; this is ${VERSION}.`,
145
- fix: `Run \`${UPDATE_COMMAND}\`, choose "Re-register with your AI client", then fully restart the client. ` +
146
- `What changed: ${RELEASES_URL}`,
152
+ fix: `The person who set this up ${updateSteps()}. What changed: ${RELEASES_URL}`,
147
153
  });
148
154
  }
149
155
  // Leftovers from before the 2.0 rename. Both keep working through 2.x,
@@ -181,13 +187,15 @@ export function registerDiagnostics(server, config) {
181
187
  check: "token_present",
182
188
  status: "fail",
183
189
  detail: "No DISCORD_TOKEN is set.",
184
- fix: "Run `npx @orygn/discord-mcp init`, or set DISCORD_TOKEN in the MCP " +
185
- `server config (env section) or in ${configFolders().map((f) => join(f, ".env")).join(" or ")}. ` +
190
+ fix: (packagedAs() === "mcpb"
191
+ ? `In Claude, open ${BUNDLE_SETTINGS}, fill in "Discord bot token" and save. `
192
+ : "Run `npx @orygn/discord-mcp init`, or set DISCORD_TOKEN in the MCP " +
193
+ `server config (env section) or in ${configFolders().map((f) => join(f, ".env")).join(" or ")}. `) +
186
194
  "Get the token from " +
187
195
  PORTAL_BOT_PAGE +
188
196
  ", Reset Token.",
189
197
  });
190
- return finishChecks(checks);
198
+ return finishChecks(checks, config);
191
199
  }
192
200
  let entered;
193
201
  try {
@@ -247,11 +255,11 @@ export function registerDiagnostics(server, config) {
247
255
  PORTAL_BOT_PAGE +
248
256
  ", Reset Token, and update DISCORD_TOKEN.",
249
257
  });
250
- return finishChecks(checks);
258
+ return finishChecks(checks, config);
251
259
  }
252
260
  // Anything else is an answer too: this is the tool people run when
253
- // something is wrong, and a dropped connection used to come back as
254
- // a bare error with every finding so far thrown away.
261
+ // something is wrong, so a dropped connection is reported as a
262
+ // finding and the findings before it are kept.
255
263
  checks.push({
256
264
  check: "discord_reachable",
257
265
  status: "fail",
@@ -259,7 +267,7 @@ export function registerDiagnostics(server, config) {
259
267
  fix: "Check this machine's network connection and https://discordstatus.com, " +
260
268
  "then run the check again.",
261
269
  });
262
- return finishChecks(checks);
270
+ return finishChecks(checks, config);
263
271
  }
264
272
  // Check 3: privileged intents. Members and Message Content gate core
265
273
  // functionality (member search, reading messages). Presence is only
@@ -360,7 +368,7 @@ export function registerDiagnostics(server, config) {
360
368
  }),
361
369
  });
362
370
  }
363
- return finishChecks(checks);
371
+ return finishChecks(checks, config);
364
372
  });
365
373
  }
366
374
  function confirmationCheck() {
@@ -407,7 +415,23 @@ function confirmationCheck() {
407
415
  (mode === "token" ? ` (${name}=token).` : "; this app has not said it can show a confirmation dialog."),
408
416
  };
409
417
  }
410
- function finishChecks(checks) {
418
+ // Settings that limit what this install does, one plain line each. They are
419
+ // choices, not problems, so they sit beside the checks and are not counted.
420
+ export function restrictionLines(config) {
421
+ const lines = [];
422
+ if (config.readOnly) {
423
+ lines.push(`Read-only (${settingSource("READ_ONLY")}): only tools that change nothing are loaded, and queued messages are not sent.`);
424
+ }
425
+ if (config.allowedServers) {
426
+ const n = config.allowedServers.size;
427
+ lines.push(`Acts only in ${n} server${n === 1 ? "" : "s"} (${settingSource("ALLOWED_SERVERS")}).`);
428
+ }
429
+ return lines;
430
+ }
431
+ function finishChecks(checks, config) {
432
+ // The usage stats line is here and not in get_bot_info: this is where
433
+ // someone, or their AI, looks to see what the install does.
434
+ const settings = [...restrictionLines(config), usageLine()];
411
435
  const fails = checks.filter((c) => c.status === "fail");
412
436
  const warns = checks.filter((c) => c.status === "warn");
413
437
  const passes = checks.length - fails.length - warns.length;
@@ -421,9 +445,10 @@ function finishChecks(checks) {
421
445
  summary += ".";
422
446
  }
423
447
  const warnings = warns.map((w) => w.detail);
448
+ const data = { checks, settings };
424
449
  return fails.length > 0
425
- ? fail(summary, { checks })
426
- : ok(summary, { checks }, warnings);
450
+ ? fail(summary, data)
451
+ : ok(summary, data, warnings);
427
452
  }
428
453
  // Translates Discord REST errors into something actionable instead of a
429
454
  // bare status code.
@@ -16,7 +16,7 @@ async function resolveForum(rest, guildId, query) {
16
16
  // The forum with its tags as they are right now. Adding, changing, or
17
17
  // removing a tag sends the whole tag list back, and the channel list it
18
18
  // would otherwise come from can be half a minute old: a tag someone added
19
- // in that time was dropped by the next edit here.
19
+ // in that time would be dropped by the next edit here.
20
20
  async function withCurrentTags(rest, forum) {
21
21
  const now = (await rest.get(Routes.channel(forum.id)));
22
22
  return { ...forum, available_tags: now.available_tags ?? [] };
@@ -383,9 +383,9 @@ export function registerForumTools(server, config) {
383
383
  // Post resolution shared by the tools above: active threads whose
384
384
  // parent is a forum, by title or ID, with the direct-ID fallback.
385
385
  async function findPost(rest, guildId, query) {
386
- // Forum and media channels: only threads under one of these are posts.
387
- // Every active thread in the server used to count, so a post tool given
388
- // a name could land on an ordinary thread in a text channel.
386
+ // Forum and media channels: only threads under one of these are posts,
387
+ // so a post tool given a name cannot land on an ordinary thread in a
388
+ // text channel.
389
389
  const forums = new Set((await getChannels(rest, guildId)).filter((c) => c.type === 15 || c.type === 16).map((c) => c.id));
390
390
  const activeResult = (await rest.get(Routes.guildActiveThreads(guildId)));
391
391
  const posts = (activeResult.threads ?? []).filter((p) => p.parent_id && forums.has(p.parent_id));
@@ -605,7 +605,7 @@ export function registerManageTools(server, config) {
605
605
  server.registerTool("pin_message", {
606
606
  title: "Pin message",
607
607
  description: "Pin a message in a channel. Needs the Pin Messages permission " +
608
- "(split from Manage Messages in 2026). Channels hold at most 50 pins.",
608
+ "(split from Manage Messages in 2026). Channels hold at most 250 pins.",
609
609
  inputSchema: {
610
610
  channel: z.string().describe("Channel name or ID."),
611
611
  guild: guildParam,
@@ -661,7 +661,7 @@ export function registerManageTools(server, config) {
661
661
  const { rest, guildId } = await enter(config, guild);
662
662
  const target = await resolveChannel(rest, guildId, channel, TEXT_BEARING_TYPES);
663
663
  // Discord hands pins out 50 at a time and a channel can hold 250, so
664
- // every page is read; the first used to be given as all of them.
664
+ // every page is read.
665
665
  const items = [];
666
666
  let before;
667
667
  let more = false;
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { channelLabel } from "../discord/grants.js";
3
3
  import { Routes, PermissionFlagsBits } from "discord-api-types/v10";
4
- import { gateDestructive } from "../safety.js";
4
+ import { gateDestructive, gateKeeping, keptFor } from "../safety.js";
5
5
  import { quoted } from "../discord/names.js";
6
6
  import { saveSchedule, listSchedules, cancelSchedule, getSchedule, } from "../scheduler.js";
7
7
  import { ok, fail } from "../envelope.js";
@@ -145,7 +145,9 @@ export function registerMessagingTools(server, config) {
145
145
  "filtered by author or text. Discord cannot bulk delete messages " +
146
146
  "older than 14 days. Safe to call directly: the first call returns " +
147
147
  "how many it would remove, with a sample of them, plus a " +
148
- "confirm_token; repeating the call with the token deletes them.",
148
+ "confirm_token; repeating the call with the token deletes those same " +
149
+ "messages. Messages posted after the preview are left alone, so it " +
150
+ "works in a busy channel, such as during a raid.",
149
151
  inputSchema: {
150
152
  channel: z.string().describe("Channel name or ID."),
151
153
  guild: guildParam,
@@ -164,13 +166,10 @@ export function registerMessagingTools(server, config) {
164
166
  const target = await resolveChannel(rest, guildId, channel, TEXT_BEARING_TYPES);
165
167
  const perms = await botPermissions(rest, guildId, target);
166
168
  requirePermissions(perms, [[P.ManageMessages, "Manage Messages"]], `in ${channelLabel(target)}`);
167
- const recent = (await rest.get(Routes.channelMessages(target.id), {
168
- query: new URLSearchParams({ limit: String(count ?? 50) }),
169
- }));
170
- const cutoff = Date.now() - 14 * 24 * 60 * 60 * 1000;
169
+ const cutoff = Date.now() - BULK_DELETE_MAX_AGE_MS;
171
170
  const authorNeedle = from_author?.toLowerCase();
172
171
  const textNeedle = contains?.toLowerCase();
173
- const eligible = recent.filter((m) => {
172
+ const matches = (m) => {
174
173
  if (new Date(m.timestamp).getTime() < cutoff)
175
174
  return false;
176
175
  if (authorNeedle &&
@@ -182,31 +181,76 @@ export function registerMessagingTools(server, config) {
182
181
  return false;
183
182
  }
184
183
  return true;
185
- });
186
- if (eligible.length === 0) {
187
- return ok("No messages in range match those filters (Discord cannot bulk " +
188
- "delete messages older than 14 days).", { deleted: 0 });
184
+ };
185
+ const where = channelLabel(target) +
186
+ (from_author ? ` from ${quoted(from_author)}` : "") +
187
+ (contains ? ` containing ${quoted(contains)}` : "");
188
+ const filtered = from_author !== undefined || contains !== undefined;
189
+ // The token is bound to the request, not to the messages: in a busy
190
+ // channel the newest messages change between the preview and the
191
+ // confirmation, and a token bound to them would be refused every time,
192
+ // which is when this tool is needed most. What the preview showed is kept
193
+ // with the token instead, and confirming deletes that and nothing else.
194
+ const bound = { channel: target.id, count: count ?? 50, from_author: from_author ?? null, contains: contains ?? null };
195
+ // Confirming: the preview's messages, as far as they are still there.
196
+ const previewed = asPreviewed(keptFor(confirm_token, BULK_DELETE, bound));
197
+ let recheck;
198
+ let planned;
199
+ let newest;
200
+ if (previewed) {
201
+ recheck = await recheckPreviewed(rest, target.id, previewed, matches);
202
+ planned = recheck.still;
203
+ if (planned.length === 0) {
204
+ return ok(`None of the ${previewed.ids.length} message(s) the preview showed are left to delete` +
205
+ leftAloneText(recheck, filtered, "open") +
206
+ " Nothing was deleted.", { deleted: 0, left_alone: leftAloneData(recheck) });
207
+ }
189
208
  }
190
- const ids = eligible.map((m) => m.id);
191
- const gate = gateDestructive({
192
- tool: "bulk_delete_messages",
193
- args: { channel: target.id, ids: ids.join(",") },
209
+ else {
210
+ const recent = (await rest.get(Routes.channelMessages(target.id), {
211
+ query: new URLSearchParams({ limit: String(count ?? 50) }),
212
+ }));
213
+ planned = recent.filter(matches);
214
+ newest = newestId(recent);
215
+ if (planned.length === 0) {
216
+ return ok("No messages in range match those filters (Discord cannot bulk " +
217
+ "delete messages older than 14 days).", { deleted: 0 });
218
+ }
219
+ }
220
+ const outcome = gateKeeping({
221
+ tool: BULK_DELETE,
222
+ args: bound,
194
223
  dryRun: dry_run,
195
224
  confirmToken: confirm_token,
196
- previewSummary: `Would delete ${ids.length} message(s) in ${channelLabel(target)}` +
197
- (from_author ? ` from ${quoted(from_author)}` : "") +
198
- (contains ? ` containing ${quoted(contains)}` : "") +
199
- ". This cannot be undone.",
225
+ previewSummary: previewed
226
+ ? `Would delete the ${planned.length} message(s) in ${where} that the preview showed.` +
227
+ leftAloneText(recheck, filtered, "will") +
228
+ " This cannot be undone."
229
+ : `Would delete ${planned.length} message(s) in ${where}. This cannot be undone.`,
230
+ note: previewed ? undefined : "Confirming deletes these messages only: any posted after this preview are left alone.",
200
231
  previewDetails: {
201
- count: ids.length,
202
- sample: eligible.slice(0, 5).map((m) => ({
232
+ count: planned.length,
233
+ sample: planned.slice(0, 5).map((m) => ({
203
234
  author: m.author.username,
204
235
  excerpt: (m.content ?? "").slice(0, 60),
205
236
  })),
237
+ ...(recheck ? { left_alone: leftAloneData(recheck) } : {}),
206
238
  },
239
+ keep: previewed ? undefined : { ids: planned.map((m) => m.id), newest: newest ?? planned[0].id },
207
240
  });
208
- if (gate)
209
- return gate;
241
+ if (outcome.answer)
242
+ return outcome.answer;
243
+ // Going ahead. With safe mode off nothing was kept, and the messages
244
+ // are the ones that match now. Otherwise they are the preview's.
245
+ const kept = asPreviewed(outcome.kept);
246
+ if (kept && kept !== previewed) {
247
+ recheck = await recheckPreviewed(rest, target.id, kept, matches);
248
+ planned = recheck.still;
249
+ }
250
+ if (planned.length === 0) {
251
+ return ok("Nothing was left to delete.", { deleted: 0, ...(recheck ? { left_alone: leftAloneData(recheck) } : {}) });
252
+ }
253
+ const ids = planned.map((m) => m.id);
210
254
  if (ids.length === 1) {
211
255
  await rest.delete(Routes.channelMessage(target.id, ids[0]));
212
256
  }
@@ -216,9 +260,7 @@ export function registerMessagingTools(server, config) {
216
260
  reason: "Bulk delete via discord-mcp",
217
261
  });
218
262
  }
219
- return ok(`Deleted ${ids.length} message(s) in ${channelLabel(target)}.`, {
220
- deleted: ids.length,
221
- });
263
+ return ok(`Deleted ${ids.length} message(s) in ${channelLabel(target)}.` + (recheck ? leftAloneText(recheck, filtered, "were") : ""), { deleted: ids.length, ...(recheck ? { left_alone: leftAloneData(recheck) } : {}) });
222
264
  }));
223
265
  server.registerTool("crosspost_message", {
224
266
  title: "Crosspost message",
@@ -247,8 +289,8 @@ export function registerMessagingTools(server, config) {
247
289
  "community event members can RSVP to, use create_event. This server " +
248
290
  "sends it when the time comes. One limit worth " +
249
291
  "knowing: delivery needs this server to be running at " +
250
- "that moment, so always-on scheduling wants the hosted or Docker " +
251
- "deployment rather than a laptop that sleeps. A message that came " +
292
+ "that moment, so always-on scheduling needs a machine or container " +
293
+ "that stays up rather than a laptop that sleeps. A message that came " +
252
294
  "due during downtime is sent at the next start.",
253
295
  inputSchema: {
254
296
  channel: z.string().describe("Channel name or ID."),
@@ -272,8 +314,7 @@ export function registerMessagingTools(server, config) {
272
314
  if ((repeat ?? "none") === "none" && when.getTime() <= Date.now()) {
273
315
  return fail("send_at is in the past. Pick a future time.");
274
316
  }
275
- // A repeat given a past start begins at its next time. Before, it
276
- // posted within half a minute of being scheduled.
317
+ // A repeat given a past start begins at its next time.
277
318
  if ((repeat ?? "none") !== "none") {
278
319
  const step = repeat === "daily" ? 86_400_000 : 604_800_000;
279
320
  const behind = Date.now() - when.getTime();
@@ -359,3 +400,85 @@ export function registerMessagingTools(server, config) {
359
400
  return ok(`Canceled scheduled message ${schedule_id}.`, { canceled: true });
360
401
  }));
361
402
  }
403
+ // Bulk deletion: what a preview keeps with its token, and how the
404
+ // confirmation finds which of those messages are still there to delete.
405
+ const BULK_DELETE = "bulk_delete_messages";
406
+ const BULK_DELETE_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
407
+ function asPreviewed(value) {
408
+ const v = value;
409
+ return v && Array.isArray(v.ids) && v.ids.length > 0 && typeof v.newest === "string" ? v : undefined;
410
+ }
411
+ function newestId(messages) {
412
+ let best;
413
+ for (const m of messages)
414
+ if (best === undefined || BigInt(m.id) > BigInt(best))
415
+ best = m.id;
416
+ return best;
417
+ }
418
+ // One page read forward from just before the oldest previewed message.
419
+ // Message ids grow with time, and the preview read at most 100 messages, so
420
+ // that page holds every previewed message still there, whatever has been
421
+ // posted since; anything newer than the preview's newest arrived later.
422
+ async function recheckPreviewed(rest, channelId, previewed, matches) {
423
+ let oldest = BigInt(previewed.ids[0]);
424
+ for (const id of previewed.ids)
425
+ if (BigInt(id) < oldest)
426
+ oldest = BigInt(id);
427
+ const page = (await rest.get(Routes.channelMessages(channelId), {
428
+ query: new URLSearchParams({ after: (oldest - 1n).toString(), limit: "100" }),
429
+ }));
430
+ const byId = new Map(page.map((m) => [m.id, m]));
431
+ const still = [];
432
+ let gone = 0;
433
+ let changed = 0;
434
+ for (const id of previewed.ids) {
435
+ const m = byId.get(id);
436
+ if (!m)
437
+ gone += 1;
438
+ else if (!matches(m))
439
+ changed += 1;
440
+ else
441
+ still.push(m);
442
+ }
443
+ const newest = BigInt(previewed.newest);
444
+ const later = page.filter((m) => BigInt(m.id) > newest && matches(m)).length;
445
+ return { still, gone, changed, later, laterCapped: page.length >= 100 };
446
+ }
447
+ function leftAloneData(r) {
448
+ return {
449
+ ...(r.later > 0 ? { posted_after_preview: r.later } : {}),
450
+ ...(r.gone > 0 ? { already_gone: r.gone } : {}),
451
+ ...(r.changed > 0 ? { no_longer_match: r.changed } : {}),
452
+ };
453
+ }
454
+ // The messages left alone, as sentences after the main one.
455
+ // open: after "None of the N the preview showed are left to delete"
456
+ // will: in the confirmation, which the dialog shows the user, so it
457
+ // states what happens and gives the model no instructions
458
+ // were: in the result, which says how to get the newer ones too
459
+ function leftAloneText(r, filtered, mode) {
460
+ // After "None of the N the preview showed", the count alone says which.
461
+ const of = mode === "open" ? "" : " of the previewed messages";
462
+ const parts = [];
463
+ if (r.gone > 0)
464
+ parts.push(`${r.gone}${of} ${r.gone === 1 ? "is" : "are"} already gone`);
465
+ if (r.changed > 0) {
466
+ parts.push(`${r.changed}${of} no longer ${r.changed === 1 ? "matches" : "match"} (edited, or now older than 14 days)`);
467
+ }
468
+ let text = mode === "open"
469
+ ? parts.length > 0 ? `: ${parts.join("; ")}.` : "."
470
+ : parts.length > 0 ? ` ${capitalize(parts.join("; "))}.` : "";
471
+ if (r.later > 0) {
472
+ const what = filtered ? "matching message(s)" : "message(s)";
473
+ const count = `${r.laterCapped ? "At least " : ""}${r.later} ${what} posted after the preview`;
474
+ const one = r.later === 1 && !r.laterCapped;
475
+ text +=
476
+ mode === "will"
477
+ ? ` ${count} ${one ? "is" : "are"} left alone.`
478
+ : ` ${count} ${one ? "was" : "were"} left alone; call again without a confirm_token for a fresh preview that includes them.`;
479
+ }
480
+ return text;
481
+ }
482
+ function capitalize(text) {
483
+ return text.charAt(0).toUpperCase() + text.slice(1);
484
+ }
@@ -251,9 +251,9 @@ export function registerModerationTools(server, config) {
251
251
  }
252
252
  member = undefined;
253
253
  }
254
- // Permission and protection checks run on every path. The earlier
255
- // version skipped both for hackbans, which also let a protected
256
- // member's raw ID slip past the owner and hierarchy rules.
254
+ // Permission and protection checks run on every path, hackbans
255
+ // included, so a protected member's raw ID cannot get past the owner
256
+ // and hierarchy rules.
257
257
  const [roles, botUser, guildData] = await Promise.all([
258
258
  getRoles(rest, guildId),
259
259
  getBotUser(rest),
@@ -508,7 +508,7 @@ export function registerModerationTools(server, config) {
508
508
  if (user) {
509
509
  // An id needs no lookup, and must not get one: someone who has left
510
510
  // or was banned still has entries, and looking them up as a member
511
- // failed before the log was ever asked.
511
+ // would fail before the log was ever asked.
512
512
  const id = user.trim().match(/^(?:<@!?)?(\d{17,20})>?$/)?.[1];
513
513
  if (id) {
514
514
  query.set("user_id", id);
@@ -160,7 +160,7 @@ async function overwriteGrants(rest, guildId, ch, target, next, found) {
160
160
  return grantsForRoleChange(now, changed, target.roleId, fresh.keys());
161
161
  }
162
162
  // The confirmation for an overwrite change that hands out power or access;
163
- // null when the change hands out neither and goes ahead as before.
163
+ // null when the change hands out neither and goes ahead at once.
164
164
  async function gateOverwrite(rest, guildId, ch, tool, target, next, found, confirmToken, what) {
165
165
  const grants = await overwriteGrants(rest, guildId, ch, target, next, found);
166
166
  if (!hasGrants(grants))
@@ -565,8 +565,8 @@ export function registerPermissionTools(server, config) {
565
565
  scope = "server-wide";
566
566
  }
567
567
  // The owner has every permission whatever their roles say. The
568
- // calculation from roles does not know that: as the fallback it
569
- // answered no for an owner, and as the explanation it credited a role.
568
+ // calculation from roles does not know that: as the fallback it would
569
+ // answer no for an owner, and as the explanation it would credit a role.
570
570
  const isOwner = (await rest.get(Routes.guild(guildId))).owner_id === actorId;
571
571
  if (isOwner)
572
572
  local = ALL_PERMISSIONS;