@orygn/discord-mcp 2.0.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 (50) hide show
  1. package/README.md +62 -19
  2. package/dist/builder/executor.js +1 -1
  3. package/dist/builder/overwrites.js +2 -2
  4. package/dist/builder/planner.js +2 -2
  5. package/dist/config.js +17 -5
  6. package/dist/discord/client.js +16 -8
  7. package/dist/discord/gateway.js +5 -8
  8. package/dist/discord/gatewayEvents.js +1 -2
  9. package/dist/discord/grants.js +2 -2
  10. package/dist/discord/guildData.js +2 -3
  11. package/dist/discord/images.js +2 -2
  12. package/dist/discord/messageImages.js +2 -2
  13. package/dist/discord/rateLimit.js +1 -3
  14. package/dist/http.js +3 -3
  15. package/dist/index.js +7 -0
  16. package/dist/install.js +7 -8
  17. package/dist/instructions.js +27 -4
  18. package/dist/lifecycle.js +15 -5
  19. package/dist/packaging.js +11 -0
  20. package/dist/restrictions.js +57 -0
  21. package/dist/safety.js +77 -32
  22. package/dist/scheduler.js +17 -9
  23. package/dist/server.js +114 -32
  24. package/dist/settings.js +3 -0
  25. package/dist/textFiles.js +8 -0
  26. package/dist/tools/appCommands.js +11 -4
  27. package/dist/tools/automod.js +1 -2
  28. package/dist/tools/botProfile.js +6 -0
  29. package/dist/tools/catchUp.js +2 -2
  30. package/dist/tools/common.js +33 -18
  31. package/dist/tools/community.js +4 -4
  32. package/dist/tools/diagnostics.js +47 -22
  33. package/dist/tools/forums.js +4 -4
  34. package/dist/tools/manage.js +2 -2
  35. package/dist/tools/messaging.js +153 -30
  36. package/dist/tools/moderation.js +4 -4
  37. package/dist/tools/permissions.js +3 -3
  38. package/dist/tools/reactions.js +2 -3
  39. package/dist/tools/read.js +1 -3
  40. package/dist/tools/realtime.js +1 -1
  41. package/dist/tools/roster.js +12 -3
  42. package/dist/tools/settings.js +2 -2
  43. package/dist/tools/write.js +2 -2
  44. package/dist/unknownArguments.js +8 -7
  45. package/dist/updateCheck.js +19 -4
  46. package/dist/usageReport.js +421 -0
  47. package/dist/usageStats.js +253 -0
  48. package/dist/wizard.js +23 -3
  49. package/dist/wizardLib.js +6 -6
  50. package/package.json +1 -1
@@ -0,0 +1,253 @@
1
+ import { accessSync, constants, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { randomBytes } from "node:crypto";
4
+ import { join } from "node:path";
5
+ import { IS_INSTALLED, dataDir } from "./home.js";
6
+ import { setting, settingSource } from "./settings.js";
7
+ import { packagedAs } from "./packaging.js";
8
+ const ON_WORDS = ["on", "true", "1", "yes"];
9
+ // Set by CI systems. A test run is never real use.
10
+ export const CI_VARIABLES = ["CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "CIRCLECI", "TF_BUILD", "JENKINS_URL", "TEAMCITY_VERSION", "BITBUCKET_BUILD_NUMBER", "CODEBUILD_BUILD_ID"];
11
+ function truthy(value) {
12
+ if (value === undefined)
13
+ return false;
14
+ const v = value.trim().toLowerCase();
15
+ return v !== "" && v !== "0" && v !== "false" && v !== "no" && v !== "off";
16
+ }
17
+ // Whether usage stats are sent, and if not, why. DISCORD_MCP_TELEMETRY set
18
+ // to anything but on (off, false, disabled, ...) turns them off, so a word
19
+ // meant as off never leaves them on. DO_NOT_TRACK and CI always win. A
20
+ // source checkout is development, so it sends nothing unless told to.
21
+ export function usageSwitch(env = process.env, installed = IS_INSTALLED || packagedAs(env) !== undefined) {
22
+ if (truthy(env.DO_NOT_TRACK))
23
+ return { on: false, why: "DO_NOT_TRACK is set" };
24
+ const ci = CI_VARIABLES.find((name) => truthy(env[name]));
25
+ if (ci)
26
+ return { on: false, why: "running in CI" };
27
+ const value = setting("TELEMETRY", env);
28
+ if (value !== undefined) {
29
+ if (ON_WORDS.includes(value.toLowerCase()))
30
+ return { on: true };
31
+ // The Claude Desktop bundle sets it from a checkbox in its settings.
32
+ return { on: false, why: packagedAs(env) === "mcpb" ? "turned off in the extension's settings" : `${settingSource("TELEMETRY", env)}=${value}` };
33
+ }
34
+ if (!installed)
35
+ return { on: false, why: "running from a source checkout" };
36
+ return { on: true };
37
+ }
38
+ // The settings line for run_setup_check: plain, one line, either way. In
39
+ // the Claude Desktop bundle the switch is a checkbox, not a variable.
40
+ export function usageLine(sw = usageSwitch(), env = process.env) {
41
+ if (!sw.on)
42
+ return `Usage stats: off (${sw.why}).`;
43
+ return packagedAs(env) === "mcpb"
44
+ ? "Usage stats: on. To turn them off, untick Usage stats in this extension's settings."
45
+ : `Usage stats: on. To turn them off, set ${settingSource("TELEMETRY", env)}=off.`;
46
+ }
47
+ // --- what is counted ---
48
+ export const ERROR_CLASSES = ["permission", "intents", "rate_limited", "not_found", "validation", "no_token", "network", "other"];
49
+ export const GATE_EVENTS = ["preview", "confirmed", "declined"];
50
+ // A failed result, sorted into a class by what it says. Only the class is
51
+ // kept, never the text.
52
+ export function errorClass(summary, data) {
53
+ if (data?.rate_limited === true || /rate.?limit/i.test(summary))
54
+ return "rate_limited";
55
+ if (/No Discord bot token/i.test(summary))
56
+ return "no_token";
57
+ if (/intent/i.test(summary))
58
+ return "intents";
59
+ if (/permission|Missing Access|not allowed to|cannot (?:manage|edit|assign|kick|ban)/i.test(summary))
60
+ return "permission";
61
+ if (/Could not reach Discord|network|ECONN|ETIMEDOUT|fetch failed/i.test(summary))
62
+ return "network";
63
+ if (/has no parameter named|does not read|Input validation|Invalid arguments|has no dry run|expected .* received/i.test(summary))
64
+ return "validation";
65
+ if (/No (?:single |configured )?\w*.{0,40}match|not found|Unknown \w+|does not exist|no longer exists|is not one of the servers/i.test(summary))
66
+ return "not_found";
67
+ return "other";
68
+ }
69
+ // The AI app, from the name it gives when it connects, as one of a fixed
70
+ // list. Order matters: Claude Code before Claude, and so on. Claude
71
+ // Desktop 5 connects to an extension as "local-agent-mode-<the server's
72
+ // name>", so that prefix comes first: what follows it is
73
+ // our own name, which could hold any word.
74
+ const APPS = [
75
+ [/^local-agent-mode-|^custom3p-/i, "claude-desktop"],
76
+ [/claude[-_ ]?code/i, "claude-code"],
77
+ [/claude/i, "claude-desktop"],
78
+ [/cursor/i, "cursor"],
79
+ [/visual studio code|vscode|vs code/i, "vscode"],
80
+ [/windsurf|codeium/i, "windsurf"],
81
+ [/^roo|roo[-_ ]?code/i, "roo-code"],
82
+ [/cline/i, "cline"],
83
+ [/codex/i, "codex"],
84
+ [/^zed/i, "zed"],
85
+ [/goose/i, "goose"],
86
+ [/continue/i, "continue"],
87
+ [/lm[-_ ]?studio/i, "lm-studio"],
88
+ [/gemini/i, "gemini-cli"],
89
+ [/kiro/i, "kiro"],
90
+ [/chatgpt|openai/i, "chatgpt"],
91
+ [/jetbrains|intellij|pycharm|webstorm/i, "jetbrains"],
92
+ [/opencode/i, "opencode"],
93
+ [/warp/i, "warp"],
94
+ [/librechat/i, "librechat"],
95
+ ];
96
+ export function appName(clientName) {
97
+ if (!clientName || !clientName.trim())
98
+ return "unknown";
99
+ for (const [pattern, name] of APPS)
100
+ if (pattern.test(clientName))
101
+ return name;
102
+ return "other";
103
+ }
104
+ // --- the running tally ---
105
+ export function utcDay(at = new Date()) {
106
+ return at.toISOString().slice(0, 10);
107
+ }
108
+ let running;
109
+ let counting = false;
110
+ let reachedDay;
111
+ let currentApp = "unknown";
112
+ let onActive;
113
+ const fileTag = `${process.pid}-${randomBytes(3).toString("hex")}`;
114
+ // Where the counts and the report's state live: the data folder, so they
115
+ // survive upgrades. Where that cannot be written (a container run without a
116
+ // volume, where the image's own folder belongs to root), the system's temp
117
+ // folder instead; those installs are labelled as containers anyway.
118
+ let resolvedDir;
119
+ export function usageDir() {
120
+ if (resolvedDir)
121
+ return resolvedDir;
122
+ const primary = join(dataDir(), "usage-stats");
123
+ try {
124
+ mkdirSync(primary, { recursive: true });
125
+ accessSync(primary, constants.W_OK);
126
+ resolvedDir = primary;
127
+ }
128
+ catch {
129
+ resolvedDir = join(tmpdir(), "discord-mcp-usage-stats");
130
+ }
131
+ return resolvedDir;
132
+ }
133
+ function emptyTally() {
134
+ return { tools: {}, gate: {}, errors: {}, apps: [] };
135
+ }
136
+ function today() {
137
+ const day = utcDay();
138
+ if (!running || running.day !== day) {
139
+ // The day turned: what is left of the old one is written before moving on.
140
+ if (running?.dirty)
141
+ flush();
142
+ running = { day, tally: emptyTally(), dirty: false, file: join(usageDir(), `day-${day}-${fileTag}.json`) };
143
+ }
144
+ return running;
145
+ }
146
+ // Writes this process's count for the day, whole, under a temporary name
147
+ // renamed into place, so the report never reads half a file.
148
+ export function flush() {
149
+ if (!running || !running.dirty)
150
+ return;
151
+ try {
152
+ mkdirSync(usageDir(), { recursive: true });
153
+ const temp = `${running.file}.tmp`;
154
+ writeFileSync(temp, JSON.stringify(running.tally));
155
+ renameSync(temp, running.file);
156
+ running.dirty = false;
157
+ }
158
+ catch {
159
+ // A folder that cannot be written just means nothing is counted.
160
+ }
161
+ }
162
+ // Written at once, every time: an app closing the server kills it outright
163
+ // (on Windows nothing runs at exit), and a file of a few hundred bytes
164
+ // costs nothing next to the call that changed it.
165
+ function changed(r) {
166
+ r.dirty = true;
167
+ flush();
168
+ }
169
+ // Turns counting on for this process. Only an install that has a bot token
170
+ // counts: a directory scanner starting the server with no token is not use.
171
+ export function startCounting(opts) {
172
+ if (!usageSwitch().on || !opts.hasBot)
173
+ return;
174
+ counting = true;
175
+ onActive = opts.onActiveDay;
176
+ pruneOldFiles();
177
+ process.once("exit", flush);
178
+ }
179
+ export function countingEnabled() {
180
+ return counting;
181
+ }
182
+ export function noteClient(clientName) {
183
+ const name = appName(clientName);
184
+ if (name !== "unknown")
185
+ currentApp = name;
186
+ }
187
+ export function currentAppName() {
188
+ return currentApp;
189
+ }
190
+ // A request to Discord that succeeded: this install is really in use today.
191
+ export function noteDiscordReached() {
192
+ reachedDay = utcDay();
193
+ }
194
+ export function noteGate(event) {
195
+ if (!counting)
196
+ return;
197
+ const r = today();
198
+ r.tally.gate[event] = (r.tally.gate[event] ?? 0) + 1;
199
+ changed(r);
200
+ }
201
+ // One tool call and how it ended. A call that succeeded on a day Discord
202
+ // was reached makes the day active, which is when the report goes out.
203
+ export function noteToolCall(tool, failed) {
204
+ if (!counting)
205
+ return;
206
+ const r = today();
207
+ r.tally.tools[tool] = (r.tally.tools[tool] ?? 0) + 1;
208
+ if (!r.tally.apps.includes(currentApp))
209
+ r.tally.apps.push(currentApp);
210
+ if (failed) {
211
+ const cls = errorClass(failed.summary, failed.data);
212
+ r.tally.errors[cls] = (r.tally.errors[cls] ?? 0) + 1;
213
+ }
214
+ changed(r);
215
+ if (!failed && reachedDay === r.day && onActive) {
216
+ const go = onActive;
217
+ setImmediate(go);
218
+ }
219
+ }
220
+ // Day files from more than a week ago are never sent; they go.
221
+ const KEEP_DAYS = 8;
222
+ function pruneOldFiles() {
223
+ try {
224
+ const dir = usageDir();
225
+ if (!existsSync(dir))
226
+ return;
227
+ const cutoff = utcDay(new Date(Date.now() - KEEP_DAYS * 86_400_000));
228
+ for (const name of readdirSync(dir)) {
229
+ const m = name.match(/^day-(\d{4}-\d{2}-\d{2})-/);
230
+ if (m && m[1] < cutoff)
231
+ rmSync(join(dir, name), { force: true });
232
+ // A temporary file left by a process that died mid-write.
233
+ if (name.endsWith(".tmp") && Date.now() - statSync(join(dir, name)).mtimeMs > 3_600_000)
234
+ rmSync(join(dir, name), { force: true });
235
+ }
236
+ }
237
+ catch {
238
+ // Nothing to prune is fine.
239
+ }
240
+ }
241
+ // For tests: the state of this process's counting, and a way to reset it.
242
+ export const __testing = {
243
+ reset() {
244
+ resolvedDir = undefined;
245
+ running = undefined;
246
+ counting = false;
247
+ reachedDay = undefined;
248
+ currentApp = "unknown";
249
+ onActive = undefined;
250
+ },
251
+ running: () => running,
252
+ fileTag,
253
+ };
package/dist/wizard.js CHANGED
@@ -3,6 +3,8 @@ import { dirname, join } from "node:path";
3
3
  import { createRequire } from "node:module";
4
4
  import { homedir } from "node:os";
5
5
  import { VERSION } from "./config.js";
6
+ import { sendSetupEvent } from "./usageReport.js";
7
+ import { usageSwitch } from "./usageStats.js";
6
8
  import { envFilePath, botsFilePath, appHome, defaultHome, legacyHome, writePrivateFile, moveLegacyHome, usingLegacyHome, IS_INSTALLED, } from "./home.js";
7
9
  import { COMMAND, PACKAGE_NAME } from "./identity.js";
8
10
  import { copyToStableHome, inNpxCache } from "./install.js";
@@ -14,6 +16,8 @@ import { CLIENT_KEY, carriedSettings, clientConfigState, claudeCodeLegacyScopes,
14
16
  // against the live API instead of hoping. The pure logic lives in
15
17
  // wizardLib.ts; this file is the conversation.
16
18
  const PORTAL = "https://discord.com/developers/applications";
19
+ // The setup walkthrough, at the point where it creates the bot in the portal.
20
+ const WALKTHROUGH_PORTAL_STEPS = "https://youtu.be/vYAdzxzLKWY?t=32";
17
21
  const packageRoot = dirname(createRequire(import.meta.url).resolve("../package.json"));
18
22
  class Cancelled extends Error {
19
23
  }
@@ -156,6 +160,8 @@ async function fetchAppInfo(token) {
156
160
  intents: readIntents(application.flags ?? 0),
157
161
  };
158
162
  }
163
+ // What the setup event reports when the wizard ends (see usageReport.ts).
164
+ const setup = { flow: "fresh", outcome: "unfinished", apps: [] };
159
165
  export async function runWizard() {
160
166
  console.log("");
161
167
  console.log(` ${bold(cyan("Discord MCP"))} ${dim("by Orygn")}`);
@@ -163,8 +169,10 @@ export async function runWizard() {
163
169
  console.log(` ${dim(`Setup v${VERSION}. Type q at any prompt to quit; nothing is`)}`);
164
170
  console.log(` ${dim("changed until it says so.")}\n`);
165
171
  try {
166
- if (await offerUpgrade())
172
+ if (await offerUpgrade()) {
173
+ setup.flow = "upgrade";
167
174
  return;
175
+ }
168
176
  const cfg = readExistingConfig();
169
177
  const hasExisting = cfg.envToken !== undefined || cfg.bots.length > 0;
170
178
  if (hasExisting) {
@@ -181,9 +189,10 @@ export async function runWizard() {
181
189
  const choice = await ask(` Choose 1-4 ${dim("[1]")}: `);
182
190
  if (choice === "4")
183
191
  throw new Cancelled();
192
+ setup.flow = choice === "2" ? "reregister" : choice === "3" ? "fresh" : "add_bot";
184
193
  // Re-registering keeps the bots and only rewrites the client entry,
185
194
  // which is the whole repair for a client pointing at a copy that no
186
- // longer exists. Without it, that repair meant redoing the setup.
195
+ // longer exists, without redoing the setup.
187
196
  if (choice === "2") {
188
197
  if (await registerClient())
189
198
  printRestartSteps();
@@ -199,13 +208,16 @@ export async function runWizard() {
199
208
  }
200
209
  catch (err) {
201
210
  if (err instanceof Cancelled) {
211
+ setup.outcome = "cancelled";
202
212
  console.log(yellow("\nSetup cancelled. Nothing was changed beyond any step already confirmed."));
203
213
  return;
204
214
  }
215
+ setup.outcome = "failed";
205
216
  throw err;
206
217
  }
207
218
  finally {
208
219
  process.stdin.pause();
220
+ await sendSetupEvent(setup).catch(() => false);
209
221
  }
210
222
  }
211
223
  // The AI clients whose config files the wizard knows how to find.
@@ -341,7 +353,8 @@ async function setupBot(opts) {
341
353
  console.log(` If you do not have this bot yet: open ${underline(PORTAL)}`);
342
354
  console.log(" New Application, name it, open the Bot page, Reset Token, copy it.");
343
355
  console.log(" Turn on all three Privileged Gateway Intents, and under Installation");
344
- console.log(" choose Guild Install only (uncheck User Install).\n");
356
+ console.log(" choose Guild Install only (uncheck User Install).");
357
+ console.log(` These steps on video: ${underline(WALKTHROUGH_PORTAL_STEPS)}\n`);
345
358
  let token = "";
346
359
  let app;
347
360
  while (!app) {
@@ -448,6 +461,8 @@ function printSnippet(entry) {
448
461
  // When the file already has a different server under the discord-mcp key,
449
462
  // it asks before replacing it. Returns false when nothing was written.
450
463
  async function writeClientEntry(target, entry) {
464
+ if (!setup.apps.includes(target.client))
465
+ setup.apps.push(target.client);
451
466
  const before = existsSync(target.path) ? readFileSync(target.path, "utf8") : undefined;
452
467
  let state;
453
468
  try {
@@ -518,16 +533,21 @@ async function registerClient() {
518
533
  await writeClientEntry(present[whereIndex - 1], entry);
519
534
  }
520
535
  else {
536
+ setup.apps.push("snippet");
521
537
  console.log("\n Add this to your client's MCP config:\n");
522
538
  printSnippet(entry);
523
539
  }
524
540
  return true;
525
541
  }
526
542
  function printRestartSteps() {
543
+ setup.outcome = "completed";
527
544
  console.log(`\n${bold("Two steps left:")}`);
528
545
  console.log(` 1. ${bold("Fully restart your AI client")}: quit it from the system tray,`);
529
546
  console.log(" not just the window. New tools only load on a full restart.");
530
547
  console.log(` 2. In a fresh chat, ask: ${cyan('"run a setup check on my Discord bot"')}`);
548
+ if (usageSwitch().on) {
549
+ console.log(dim("\n Anonymous usage stats are on; DISCORD_MCP_TELEMETRY=off turns them off."));
550
+ }
531
551
  console.log("");
532
552
  }
533
553
  // A single bot supersedes any prior bots.json, so remove it: the one .env
package/dist/wizardLib.js CHANGED
@@ -2,6 +2,7 @@ import { existsSync, readdirSync, realpathSync } from "node:fs";
2
2
  import { basename, dirname, join, resolve } from "node:path";
3
3
  import { PermissionFlagsBits } from "discord-api-types/v10";
4
4
  import { PERMISSION_PRESETS } from "./discord/preflight.js";
5
+ import { withoutBom } from "./textFiles.js";
5
6
  // The pure half of the setup wizard. Everything here is a function of its
6
7
  // inputs so the logic that touches user config files is unit tested
7
8
  // without a terminal or a filesystem.
@@ -20,7 +21,7 @@ export function isOurEntry(entry) {
20
21
  function parseConfigObject(existingText) {
21
22
  if (!existingText || existingText.trim().length === 0)
22
23
  return {};
23
- const parsed = JSON.parse(existingText);
24
+ const parsed = JSON.parse(withoutBom(existingText));
24
25
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
25
26
  throw new Error("Config file is not a JSON object.");
26
27
  }
@@ -63,9 +64,8 @@ export function mergeClientConfig(existingText, entry, options = {}) {
63
64
  // What the user added to this server's entry by hand and a rewrite must
64
65
  // not lose: an env block (a toolset selection, a token, a custom home) and
65
66
  // the app's own flags on the entry (disabled, autoApprove, and the like).
66
- // Only command and args are the wizard's to write. Before, re-registering
67
- // or upgrading from Omnicord wrote a bare entry, and a server set up
68
- // through env came back with no token or with every tool loaded.
67
+ // Only command and args are the wizard's to write. A bare entry would leave
68
+ // a server set up through env with no token, or with every tool loaded.
69
69
  //
70
70
  // Taken from the discord-mcp entry when it is this server's, otherwise
71
71
  // from the pre-2.0 entry. Someone else's server under the discord-mcp key
@@ -326,7 +326,7 @@ export function parseBotsFile(content) {
326
326
  return [];
327
327
  let parsed;
328
328
  try {
329
- parsed = JSON.parse(content);
329
+ parsed = JSON.parse(withoutBom(content));
330
330
  }
331
331
  catch {
332
332
  return [];
@@ -387,7 +387,7 @@ export function botsFileServers(content) {
387
387
  if (!content || !content.trim())
388
388
  return undefined;
389
389
  try {
390
- const servers = JSON.parse(content)?.servers;
390
+ const servers = JSON.parse(withoutBom(content))?.servers;
391
391
  return servers && typeof servers === "object" && !Array.isArray(servers)
392
392
  ? servers
393
393
  : undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orygn/discord-mcp",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Discord server management MCP for AI agents: chat, moderation, admin, and full server building. Formerly Omnicord.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",