@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
package/dist/safety.js CHANGED
@@ -5,6 +5,7 @@ import { getActingBot, getTargetServer, getTargetServerId } from "./discord/acti
5
5
  import { appCanShowDialog, currentRequest } from "./requestContext.js";
6
6
  import { quoted, visibleOnly } from "./discord/names.js";
7
7
  import { setting, settingSource } from "./settings.js";
8
+ import { noteGate } from "./usageStats.js";
8
9
  // The confirmation gate for destructive operations, per tool-catalog 1.4.
9
10
  //
10
11
  // Flow: a destructive call without a valid confirm_token does not execute.
@@ -66,7 +67,7 @@ export function confirmInstruction(next, dialog = confirmsInDialog()) {
66
67
  "The dialog does the asking, so you can go ahead without asking in the chat first.");
67
68
  }
68
69
  // The last sentence closes the way a planted message gets through: a
69
- // user who trusts it says "do what it says", and the model counted that
70
+ // user who trusts it says "do what it says", and a model would count that
70
71
  // as the user asking for the change itself.
71
72
  return (`Show the user this preview and get their answer before ${next}. Skip ` +
72
73
  "asking only when their own message asked for exactly this and nothing " +
@@ -103,22 +104,43 @@ function sweepExpired(now) {
103
104
  dialogs.delete(id);
104
105
  }
105
106
  }
107
+ // What a confirm_token's preview kept, while the token is still good for
108
+ // this exact request, so a tool can describe the action it confirms (in the
109
+ // dialog, say) before the gate decides. A token from another request gives
110
+ // nothing, and the gate then refuses it. Deciding is still the gate's: this
111
+ // changes nothing.
112
+ export function keptFor(token, tool, args) {
113
+ if (!token)
114
+ return undefined;
115
+ const entry = pending.get(token);
116
+ if (!entry || entry.tool !== tool || entry.expiresAt <= Date.now())
117
+ return undefined;
118
+ if (entry.argsHash !== hashAction(tool, args, getActingBot()?.bot, getTargetServerId()))
119
+ return undefined;
120
+ return entry.kept;
121
+ }
106
122
  // Returns null when the caller may proceed with the real operation, or a
107
123
  // finished result (preview, token, dialog request, or rejection) to return
108
124
  // as is.
109
125
  export function gateDestructive(input) {
126
+ return gateKeeping(input).answer;
127
+ }
128
+ // gateDestructive, for a tool that passes keep: when the action may go
129
+ // ahead, kept is what that token's preview kept.
130
+ export function gateKeeping(input) {
110
131
  const now = Date.now();
111
132
  sweepExpired(now);
112
133
  const acting = getActingBot();
113
134
  const argsHash = hashAction(input.tool, input.args, acting?.bot, getTargetServerId());
114
135
  const safe = safeModeEnabled();
115
- // dry_run always wins. Passed together with a token, the call used to go
116
- // ahead for real, which is the opposite of what a dry run is asked for.
117
- // The token is neither checked nor spent, so the same call without
118
- // dry_run still goes ahead.
136
+ // dry_run always wins, even passed together with a token. The token is
137
+ // neither checked nor spent, so the same call without dry_run still goes
138
+ // ahead.
119
139
  if (input.dryRun && input.confirmToken) {
120
- return ok(`Dry run: nothing was changed, because dry_run was passed along with the confirm_token. ${input.previewSummary} ` +
121
- "To go ahead, call again with the confirm_token and without dry_run.", { executed: false, preview: input.previewDetails ?? null });
140
+ return {
141
+ answer: ok(`Dry run: nothing was changed, because dry_run was passed along with the confirm_token. ${input.previewSummary} ` +
142
+ "To go ahead, call again with the confirm_token and without dry_run.", { executed: false, preview: input.previewDetails ?? null }),
143
+ };
122
144
  }
123
145
  // The app is calling back with the user's answer to a dialog this gate
124
146
  // asked for. The answer decides; nothing else is consulted.
@@ -130,43 +152,52 @@ export function gateDestructive(input) {
130
152
  const refuse = safe && !dialog && confirmMode() === "dialog";
131
153
  if (input.dialogOnly) {
132
154
  if (dialog)
133
- return askInDialog(input, argsHash);
155
+ return { answer: askInDialog(input, argsHash) };
134
156
  if (refuse)
135
- return refuseWithoutDialog(input);
136
- return null;
157
+ return { answer: refuseWithoutDialog(input) };
158
+ return { answer: null };
137
159
  }
138
160
  if (input.confirmToken) {
139
161
  const entry = pending.get(input.confirmToken);
140
162
  if (!entry) {
141
- return fail("That confirm_token is unknown or was already used. Call the tool " +
142
- "again without a token to get a fresh preview.");
163
+ return {
164
+ answer: fail("That confirm_token is unknown or was already used. Call the tool " +
165
+ "again without a token to get a fresh preview."),
166
+ };
143
167
  }
144
168
  if (entry.expiresAt <= now) {
145
169
  pending.delete(input.confirmToken);
146
- return fail("That confirm_token expired. Call the tool again without a token " +
147
- "to get a fresh preview.");
170
+ return {
171
+ answer: fail("That confirm_token expired. Call the tool again without a token " +
172
+ "to get a fresh preview."),
173
+ };
148
174
  }
149
175
  if (entry.tool !== input.tool || entry.argsHash !== argsHash) {
150
- return fail("That confirm_token was issued for a different action. Tokens are " +
151
- "bound to the exact operation they previewed.");
176
+ return {
177
+ answer: fail("That confirm_token was issued for a different action. Tokens are " +
178
+ "bound to the exact operation they previewed."),
179
+ };
152
180
  }
153
181
  if (dialog)
154
- return askInDialog(input, argsHash, input.confirmToken);
182
+ return { answer: askInDialog(input, argsHash, input.confirmToken, entry.kept) };
155
183
  pending.delete(input.confirmToken);
156
184
  if (refuse)
157
- return refuseWithoutDialog(input);
158
- return null;
185
+ return { answer: refuseWithoutDialog(input) };
186
+ noteGate("confirmed");
187
+ return { answer: null, kept: entry.kept };
159
188
  }
160
189
  if (input.dryRun || safe) {
161
190
  if (refuse)
162
- return refuseWithoutDialog(input);
191
+ return { answer: refuseWithoutDialog(input) };
163
192
  const token = randomBytes(16).toString("hex");
164
193
  const ttl = input.ttlMs ?? TOKEN_TTL_MS;
165
194
  pending.set(token, {
166
195
  tool: input.tool,
167
196
  argsHash,
168
197
  expiresAt: now + ttl,
198
+ ...(input.keep !== undefined ? { kept: input.keep } : {}),
169
199
  });
200
+ noteGate("preview");
170
201
  const mode = input.dryRun ? "Dry run" : "Safe mode";
171
202
  // With more than one bot, name the acting bot and server up front so the
172
203
  // human confirming sees exactly which bot would act where. This is the
@@ -174,18 +205,20 @@ export function gateDestructive(input) {
174
205
  const summary = acting
175
206
  ? `Acting as ${acting.bot} in ${quoted(acting.server)}. ${input.previewSummary}`
176
207
  : input.previewSummary;
177
- return ok(`${mode}: nothing was changed. ${summary} ` +
178
- (input.note ? `${input.note} ` : "") +
179
- confirmInstruction("calling again with the confirm_token", dialog), {
180
- executed: false,
181
- preview: input.previewDetails ?? null,
182
- ...(acting ? { acting } : {}),
183
- confirm_token: token,
184
- token_expires_in_seconds: ttl / 1000,
185
- confirmed_by: dialog ? "dialog" : "token",
186
- });
208
+ return {
209
+ answer: ok(`${mode}: nothing was changed. ${summary} ` +
210
+ (input.note ? `${input.note} ` : "") +
211
+ confirmInstruction("calling again with the confirm_token", dialog), {
212
+ executed: false,
213
+ preview: input.previewDetails ?? null,
214
+ ...(acting ? { acting } : {}),
215
+ confirm_token: token,
216
+ token_expires_in_seconds: ttl / 1000,
217
+ confirmed_by: dialog ? "dialog" : "token",
218
+ }),
219
+ };
187
220
  }
188
- return null;
221
+ return { answer: null };
189
222
  }
190
223
  // The dialog's text, written from the resolved target, never from anything
191
224
  // the model wrote.
@@ -204,13 +237,14 @@ function dialogMessage(input) {
204
237
  }
205
238
  return visibleOnly([where, input.dialogSummary ?? input.previewSummary, ...shown].filter(Boolean).join("\n"));
206
239
  }
207
- function askInDialog(input, argsHash, token) {
240
+ function askInDialog(input, argsHash, token, kept) {
208
241
  const id = randomBytes(16).toString("hex");
209
242
  dialogs.set(id, {
210
243
  tool: input.tool,
211
244
  argsHash,
212
245
  expiresAt: Date.now() + DIALOG_TTL_MS,
213
246
  ...(token ? { token } : {}),
247
+ ...(kept !== undefined ? { kept } : {}),
214
248
  });
215
249
  return inputRequired({
216
250
  inputRequests: {
@@ -233,6 +267,17 @@ function askInDialog(input, argsHash, token) {
233
267
  });
234
268
  }
235
269
  function answerFromDialog(input, argsHash, id) {
270
+ // Read before the answer is taken, which removes the dialog.
271
+ const kept = dialogs.get(id)?.kept;
272
+ const answer = dialogAnswer(input, argsHash, id);
273
+ const said = answer?.content?.[0]?.text ?? "";
274
+ if (answer === null)
275
+ noteGate("confirmed");
276
+ else if (/"confirmation": "(?:declined|not_ticked|cancelled)"/.test(said))
277
+ noteGate("declined");
278
+ return answer === null ? { answer, kept } : { answer };
279
+ }
280
+ function dialogAnswer(input, argsHash, id) {
236
281
  const entry = dialogs.get(id);
237
282
  if (!entry || entry.expiresAt <= Date.now()) {
238
283
  dialogs.delete(id);
package/dist/scheduler.js CHANGED
@@ -4,14 +4,14 @@ import { join } from "node:path";
4
4
  import { Routes } from "discord-api-types/v10";
5
5
  import { getRest, getRestForToken } from "./discord/client.js";
6
6
  import { dataDir } from "./home.js";
7
- import { setting } from "./settings.js";
7
+ import { setting, settingSource } from "./settings.js";
8
8
  // The message scheduler. Schedules persist as JSON files so they survive a
9
9
  // restart, and the engine fires them with a periodic tick while the
10
10
  // process is alive. A message that came due while the server was off is sent
11
11
  // on the next start (catch-up), then either removed or advanced to its
12
- // next repeat. This is honest about its one limit: nothing fires while the
13
- // process is down, so always-on delivery wants the hosted or container
14
- // deployment, not a laptop that sleeps.
12
+ // next repeat. Its one limit: nothing fires while the process is down, so
13
+ // always-on delivery needs a machine or container that stays up, not a
14
+ // laptop that sleeps.
15
15
  // Default tick is half a minute, fine for human-scheduled messages.
16
16
  // Overridable so tests can run the loop fast.
17
17
  function tickMs() {
@@ -97,8 +97,7 @@ function cancelMark(id) {
97
97
  }
98
98
  // Cancels a schedule. One that is being sent at this moment cannot be
99
99
  // stopped, but a mark is left so a repeat does not come back afterwards
100
- // (completeClaim checks it); before, cancelling then answered "no such
101
- // message" and the repeat carried on.
100
+ // (completeClaim checks it).
102
101
  export function cancelSchedule(id) {
103
102
  if (!ID_PATTERN.test(id))
104
103
  return false;
@@ -231,9 +230,8 @@ let running = false;
231
230
  // Schedules already complained about in this process, so a message whose
232
231
  // bot is gone is logged once, not every tick.
233
232
  const complained = new Set();
234
- // The client that sends a schedule: the bot that scheduled it. A message
235
- // scheduled by a bot other than the default used to go out through the
236
- // default bot, which may not be in that server at all.
233
+ // The client that sends a schedule: the bot that scheduled it, since the
234
+ // default bot may not be in that server at all.
237
235
  function restFor(config, schedule) {
238
236
  if (!schedule.bot)
239
237
  return config.token ? getRest(config) : undefined;
@@ -251,6 +249,16 @@ async function tick(config) {
251
249
  continue;
252
250
  if (listed.failed && listed.repeat === "none")
253
251
  continue;
252
+ // Queued before the allowed servers were set, for a server outside
253
+ // them: not sent, and kept, so lifting the restriction sends it.
254
+ if (config.allowedServers && !config.allowedServers.has(listed.guild_id)) {
255
+ if (!complained.has(listed.id)) {
256
+ complained.add(listed.id);
257
+ console.error(`discord-mcp scheduler: ${listed.id} is for a server outside ${settingSource("ALLOWED_SERVERS")}, ` +
258
+ "so it is not sent. It stays queued; cancel it, or allow that server.");
259
+ }
260
+ continue;
261
+ }
254
262
  const rest = restFor(config, listed);
255
263
  if (!rest) {
256
264
  if (!complained.has(listed.id)) {
package/dist/server.js CHANGED
@@ -32,6 +32,7 @@ import { registerAppCommandTools } from "./tools/appCommands.js";
32
32
  import { registerBotProfileTools } from "./tools/botProfile.js";
33
33
  import { registerAuditTools } from "./tools/audit.js";
34
34
  import { registerCatchUpTools } from "./tools/catchUp.js";
35
+ import { noteClient, noteToolCall } from "./usageStats.js";
35
36
  // Applies the toolset selection, the request scope the safety gate reads,
36
37
  // and the answer to a parameter a tool does not have, without touching the
37
38
  // tool modules.
@@ -59,6 +60,27 @@ function applyToolsets(server, allowed) {
59
60
  // as the callback's last argument.
60
61
  const clientCapabilities = () => server.server.getClientCapabilities();
61
62
  const inRequest = (callback) => (...a) => runInRequest({ ctx: a[a.length - 1], clientCapabilities }, () => callback(...a));
63
+ // Each call is counted for the usage stats under the tool's name, with
64
+ // the class of error when it failed (see usageStats.ts). Nothing from
65
+ // the arguments or the result is kept.
66
+ const clientName = (ctx) => {
67
+ const envelope = ctx?.mcpReq?.envelope;
68
+ const fromEnvelope = envelope?.["io.modelcontextprotocol/clientInfo"]?.name;
69
+ return typeof fromEnvelope === "string" ? fromEnvelope : server.server.getClientVersion()?.name;
70
+ };
71
+ const counted = (name, callback) => async (...a) => {
72
+ noteClient(clientName(a[a.length - 1]));
73
+ let result;
74
+ try {
75
+ result = await callback(...a);
76
+ }
77
+ catch (err) {
78
+ noteToolCall(name, { summary: String(err), data: {} });
79
+ throw err;
80
+ }
81
+ noteToolCall(name, failureOf(result));
82
+ return result;
83
+ };
62
84
  return new Proxy(server, {
63
85
  get(target, prop) {
64
86
  if (prop === "registerTool") {
@@ -74,7 +96,7 @@ function applyToolsets(server, allowed) {
74
96
  const answering = last > 0 ? answeringUnknown(name, rest[0], run) : undefined;
75
97
  if (answering)
76
98
  rest[0] = answering.def;
77
- rest[last] = answering ? answering.run : run;
99
+ rest[last] = counted(name, answering ? answering.run : run);
78
100
  }
79
101
  return target.registerTool(name, ...rest);
80
102
  };
@@ -86,41 +108,101 @@ function applyToolsets(server, allowed) {
86
108
  },
87
109
  });
88
110
  }
111
+ // A failed tool result's summary and data, for sorting the failure into a
112
+ // class. Undefined for anything that did not fail.
113
+ function failureOf(result) {
114
+ const r = result;
115
+ if (r?.isError !== true)
116
+ return undefined;
117
+ const text = r.content?.[0]?.type === "text" ? (r.content[0].text ?? "") : "";
118
+ try {
119
+ const envelope = JSON.parse(text);
120
+ return { summary: typeof envelope.summary === "string" ? envelope.summary : "", data: envelope.data };
121
+ }
122
+ catch {
123
+ return { summary: text, data: undefined };
124
+ }
125
+ }
126
+ // Every tool module, in registration order.
127
+ const REGISTRARS = [
128
+ registerDiagnostics,
129
+ registerReadTools,
130
+ registerWriteTools,
131
+ registerBuilderTools,
132
+ registerManageTools,
133
+ registerModerationTools,
134
+ registerReactionTools,
135
+ registerCommunityTools,
136
+ registerEventTools,
137
+ registerRealtimeTools,
138
+ registerThreadTools,
139
+ registerForumTools,
140
+ registerAutomodTools,
141
+ registerSettingsTools,
142
+ registerExpressionTools,
143
+ registerBlueprintTools,
144
+ registerChangeTools,
145
+ registerMessagingTools,
146
+ registerMemberTools,
147
+ registerPermissionTools,
148
+ registerStructureTools,
149
+ registerStageTools,
150
+ registerRosterTools,
151
+ registerAppCommandTools,
152
+ registerBotProfileTools,
153
+ registerAuditTools,
154
+ registerCatchUpTools,
155
+ ];
156
+ // The tools that declare readOnlyHint: true, learned by letting every module
157
+ // register into a recorder that keeps only the names and annotations.
158
+ // Registering does nothing else (stateless HTTP builds a fresh server per
159
+ // request on the same basis), and the annotations never depend on the
160
+ // config, so this runs once per process. A tool without the annotation
161
+ // counts as one that changes something.
162
+ let readOnlyNames;
163
+ export function readOnlyToolNames(config) {
164
+ if (readOnlyNames)
165
+ return readOnlyNames;
166
+ const names = new Set();
167
+ const recorder = {
168
+ registerTool(name, def) {
169
+ if (def?.annotations?.readOnlyHint === true)
170
+ names.add(name);
171
+ return undefined;
172
+ },
173
+ };
174
+ for (const register of REGISTRARS)
175
+ register(recorder, config);
176
+ readOnlyNames = names;
177
+ return names;
178
+ }
179
+ // What this install offers: the selected tool groups, narrowed to the tools
180
+ // that change nothing in read-only mode.
181
+ export function effectiveTools(config) {
182
+ if (!config.readOnly)
183
+ return config.toolsets.tools;
184
+ const readOnly = readOnlyToolNames(config);
185
+ return new Set([...config.toolsets.tools].filter((name) => readOnly.has(name)));
186
+ }
89
187
  // Builds a fully wired McpServer. A factory rather than a singleton because
90
188
  // stateless HTTP answers each request with a fresh instance, while stdio
91
189
  // pins one instance for the whole connection.
92
190
  export function buildServer(config) {
93
- const real = new McpServer({ ...SERVER_INFO, version: VERSION }, { instructions: serverInstructions({ tools: config.toolsets.tools, safeMode: safeModeEnabled(), strictParams: strictParams() }) });
94
- // With no DISCORD_MCP_TOOLS set the selection holds every tool, so this is a
95
- // pass-through and the registered surface is identical to before.
96
- const server = applyToolsets(real, config.toolsets.tools);
97
- registerDiagnostics(server, config);
98
- registerReadTools(server, config);
99
- registerWriteTools(server, config);
100
- registerBuilderTools(server, config);
101
- registerManageTools(server, config);
102
- registerModerationTools(server, config);
103
- registerReactionTools(server, config);
104
- registerCommunityTools(server, config);
105
- registerEventTools(server, config);
106
- registerRealtimeTools(server, config);
107
- registerThreadTools(server, config);
108
- registerForumTools(server, config);
109
- registerAutomodTools(server, config);
110
- registerSettingsTools(server, config);
111
- registerExpressionTools(server, config);
112
- registerBlueprintTools(server, config);
113
- registerChangeTools(server, config);
114
- registerMessagingTools(server, config);
115
- registerMemberTools(server, config);
116
- registerPermissionTools(server, config);
117
- registerStructureTools(server, config);
118
- registerStageTools(server, config);
119
- registerRosterTools(server, config);
120
- registerAppCommandTools(server, config);
121
- registerBotProfileTools(server, config);
122
- registerAuditTools(server, config);
123
- registerCatchUpTools(server, config);
191
+ const tools = effectiveTools(config);
192
+ const real = new McpServer({ ...SERVER_INFO, version: VERSION }, {
193
+ instructions: serverInstructions({
194
+ tools,
195
+ safeMode: safeModeEnabled(),
196
+ strictParams: strictParams(),
197
+ readOnly: config.readOnly === true,
198
+ }),
199
+ });
200
+ // With no DISCORD_MCP_TOOLS set and read-only mode off the selection holds
201
+ // every tool, so this is a pass-through and the registered surface is
202
+ // identical to before.
203
+ const server = applyToolsets(real, tools);
204
+ for (const register of REGISTRARS)
205
+ register(server, config);
124
206
  // Hand back the real server: the proxy exists only to gate registration.
125
207
  return real;
126
208
  }
package/dist/settings.js CHANGED
@@ -24,6 +24,9 @@ export const SETTING_NAMES = [
24
24
  "ALLOW_PRIVATE_URLS",
25
25
  "UPDATE_CHECK",
26
26
  "STRICT_PARAMS",
27
+ "READ_ONLY",
28
+ "ALLOWED_SERVERS",
29
+ "TELEMETRY",
27
30
  ];
28
31
  // The variable a setting is actually read from: the new name, unless only
29
32
  // the old name is present.
@@ -0,0 +1,8 @@
1
+ // Text from a file someone may have edited by hand. On Windows that file can
2
+ // start with a byte order mark: PowerShell 5 writes one with
3
+ // Set-Content -Encoding UTF8, and Notepad offers "UTF-8 with BOM". JSON.parse
4
+ // refuses it, so a bots.json or an AI client's config saved that way would
5
+ // read as broken. Dropping it changes nothing else in the text.
6
+ export function withoutBom(text) {
7
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
8
+ }
@@ -3,6 +3,7 @@ import { z } from "zod";
3
3
  import { Routes, ApplicationCommandOptionType } from "discord-api-types/v10";
4
4
  import { gateDestructive } from "../safety.js";
5
5
  import { ok, fail } from "../envelope.js";
6
+ import { settingSource } from "../settings.js";
6
7
  import { enter, enterBot, guarded, guildParam, botParam, ToolProblem, confirmTokenParam } from "./common.js";
7
8
  // Slash commands belong to the Discord application, not to a server, so these
8
9
  // tools authorise on owning the application rather than on a guild permission.
@@ -72,11 +73,17 @@ async function applicationId(rest) {
72
73
  }
73
74
  // Where a command lives. Passing a guild routes through the normal guild
74
75
  // resolution, so the bot that is actually in that server does the work.
75
- async function scope(config, guild, bot) {
76
+ async function scope(config, guild, bot, changes = false) {
76
77
  if (guild) {
77
78
  const entered = await enter(config, guild, bot);
78
79
  return { rest: entered.rest, guildId: entered.guildId, where: entered.guildName };
79
80
  }
81
+ // A global command shows up in every server the bot is in, so an install
82
+ // kept to some servers does not change one.
83
+ if (changes && config.allowedServers) {
84
+ throw new ToolProblem(fail(`A global command would show up in every server the bot is in, and this install may act only in the servers in ` +
85
+ `${settingSource("ALLOWED_SERVERS")}. Pass guild to change a command in one of them. Nothing was done.`));
86
+ }
80
87
  const { rest } = enterBot(config, bot);
81
88
  return { rest, where: "globally" };
82
89
  }
@@ -138,7 +145,7 @@ export function registerAppCommandTools(server, config) {
138
145
  },
139
146
  annotations: { readOnlyHint: false, destructiveHint: false },
140
147
  }, guarded(async ({ name, description, options, guild, bot }) => {
141
- const { rest, guildId, where } = await scope(config, guild, bot);
148
+ const { rest, guildId, where } = await scope(config, guild, bot, true);
142
149
  const appId = await applicationId(rest);
143
150
  const clean = name.trim().replace(/^\//, "").toLowerCase();
144
151
  const created = (await rest.post(commandsRoute(appId, guildId), {
@@ -165,7 +172,7 @@ export function registerAppCommandTools(server, config) {
165
172
  },
166
173
  annotations: { readOnlyHint: false, destructiveHint: false },
167
174
  }, guarded(async ({ command, description, options, guild, bot }) => {
168
- const { rest, guildId, where } = await scope(config, guild, bot);
175
+ const { rest, guildId, where } = await scope(config, guild, bot, true);
169
176
  const appId = await applicationId(rest);
170
177
  const found = await resolveCommand(rest, appId, guildId, command);
171
178
  const body = {};
@@ -196,7 +203,7 @@ export function registerAppCommandTools(server, config) {
196
203
  },
197
204
  annotations: { readOnlyHint: false, destructiveHint: true },
198
205
  }, guarded(async ({ command, guild, bot, dry_run, confirm_token }) => {
199
- const { rest, guildId, where } = await scope(config, guild, bot);
206
+ const { rest, guildId, where } = await scope(config, guild, bot, true);
200
207
  const appId = await applicationId(rest);
201
208
  const found = await resolveCommand(rest, appId, guildId, command);
202
209
  const gate = gateDestructive({
@@ -151,8 +151,7 @@ export function registerAutomodTools(server, config) {
151
151
  return fail("The alert action needs an alert_channel.");
152
152
  }
153
153
  // Exempt roles and channels by name or id, like every other
154
- // reference. They used to go to Discord as written, so a name was
155
- // refused as an invalid id.
154
+ // reference. Discord itself takes only ids.
156
155
  const exemptRoleIds = [];
157
156
  if (exempt_roles?.length) {
158
157
  const roles = await getRoles(rest, guildId);
@@ -11,6 +11,7 @@ import { cancelSchedule, listSchedules } from "../scheduler.js";
11
11
  import { gateDestructive } from "../safety.js";
12
12
  import { quoted } from "../discord/names.js";
13
13
  import { ok, fail } from "../envelope.js";
14
+ import { settingSource } from "../settings.js";
14
15
  import { botParam, botPermissions, confirmTokenParam, enter, enterBot, guarded, guildParam, requirePermissions, ToolProblem, } from "./common.js";
15
16
  // The bot itself: how it looks, in one server or everywhere, and which
16
17
  // servers it stays in.
@@ -98,6 +99,11 @@ export function registerBotProfileTools(server, config) {
98
99
  if (!everywhere && username !== undefined) {
99
100
  return fail("username is the same in every server. Pass scope everywhere to change it, or nickname for one server.");
100
101
  }
102
+ // The bot's own profile shows in every server it is in.
103
+ if (everywhere && config.allowedServers) {
104
+ return fail("The bot's own profile shows in every server it is in, and this install may act only in the servers in " +
105
+ `${settingSource("ALLOWED_SERVERS")}. Use scope server to change how it looks in one of them. Nothing was changed.`);
106
+ }
101
107
  const body = {};
102
108
  const changes = [];
103
109
  for (const [field, url, label] of [
@@ -48,8 +48,8 @@ export function activeSince(channels, since, names) {
48
48
  // the Message Content intent, text, embeds, attachments, and components
49
49
  // all arrive empty. Join notices, boosts, pins, stickers, forwards, and
50
50
  // polls are empty in their own way with the intent on, so they do not
51
- // count; counting them told people their intent was off because a few
52
- // members had joined.
51
+ // count; counting them would tell people their intent was off because a
52
+ // few members had joined.
53
53
  export function looksStripped(m, botId) {
54
54
  if (m.author.id === botId)
55
55
  return false;