@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.
- package/README.md +62 -19
- package/dist/builder/executor.js +1 -1
- package/dist/builder/overwrites.js +2 -2
- package/dist/builder/planner.js +2 -2
- package/dist/config.js +17 -5
- package/dist/discord/client.js +16 -8
- package/dist/discord/gateway.js +5 -8
- package/dist/discord/gatewayEvents.js +1 -2
- package/dist/discord/grants.js +2 -2
- package/dist/discord/guildData.js +2 -3
- package/dist/discord/images.js +2 -2
- package/dist/discord/messageImages.js +2 -2
- package/dist/discord/rateLimit.js +1 -3
- package/dist/http.js +3 -3
- package/dist/index.js +7 -0
- package/dist/install.js +7 -8
- package/dist/instructions.js +27 -4
- package/dist/lifecycle.js +15 -5
- package/dist/packaging.js +11 -0
- package/dist/restrictions.js +57 -0
- package/dist/safety.js +77 -32
- package/dist/scheduler.js +17 -9
- package/dist/server.js +114 -32
- package/dist/settings.js +3 -0
- package/dist/textFiles.js +8 -0
- package/dist/tools/appCommands.js +11 -4
- package/dist/tools/automod.js +1 -2
- package/dist/tools/botProfile.js +6 -0
- package/dist/tools/catchUp.js +2 -2
- package/dist/tools/common.js +33 -18
- package/dist/tools/community.js +4 -4
- package/dist/tools/diagnostics.js +47 -22
- package/dist/tools/forums.js +4 -4
- package/dist/tools/manage.js +2 -2
- package/dist/tools/messaging.js +153 -30
- package/dist/tools/moderation.js +4 -4
- package/dist/tools/permissions.js +3 -3
- package/dist/tools/reactions.js +2 -3
- package/dist/tools/read.js +1 -3
- package/dist/tools/realtime.js +1 -1
- package/dist/tools/roster.js +12 -3
- package/dist/tools/settings.js +2 -2
- package/dist/tools/write.js +2 -2
- package/dist/unknownArguments.js +8 -7
- package/dist/updateCheck.js +19 -4
- package/dist/usageReport.js +421 -0
- package/dist/usageStats.js +253 -0
- package/dist/wizard.js +23 -3
- package/dist/wizardLib.js +6 -6
- package/package.json +1 -1
package/dist/tools/reactions.js
CHANGED
|
@@ -40,9 +40,8 @@ export function registerReactionTools(server, config) {
|
|
|
40
40
|
[P.ReadMessageHistory, "Read Message History"],
|
|
41
41
|
], `in ${channelLabel(target)}`);
|
|
42
42
|
// Every emoji is worked out before the first reaction goes on, from one
|
|
43
|
-
// read of the server's emoji
|
|
44
|
-
//
|
|
45
|
-
// word that they had been.
|
|
43
|
+
// read of the server's emoji, so a name that matches nothing fails the
|
|
44
|
+
// call before any reaction is added.
|
|
46
45
|
const guildEmojis = (await rest.get(Routes.guildEmojis(guildId)));
|
|
47
46
|
const wanted = [];
|
|
48
47
|
for (const input of emojis)
|
package/dist/tools/read.js
CHANGED
|
@@ -7,7 +7,7 @@ import { rankCandidates, resolveOne } from "../discord/resolve.js";
|
|
|
7
7
|
import { compareRolesLowToHigh } from "../discord/preflight.js";
|
|
8
8
|
import { ok, fail } from "../envelope.js";
|
|
9
9
|
import { enter, guarded, guildParam, resolveChannel, resolveMember, memberDisplayName, memberResolvable, messageIdParam, digestMessage, hiddenChannelSummary, TEXT_BEARING_TYPES, imagesHint, } from "./common.js";
|
|
10
|
-
// Read-only tools
|
|
10
|
+
// Read-only tools. Everything in this file can be called
|
|
11
11
|
// freely; nothing here changes any state on Discord.
|
|
12
12
|
// Roles whose permission digests are worth surfacing. The full bitfield is
|
|
13
13
|
// sixty-plus flags of noise; these are the ones a human asks about.
|
|
@@ -385,8 +385,6 @@ export function registerReadTools(server, config) {
|
|
|
385
385
|
let members = [];
|
|
386
386
|
const warnings = [];
|
|
387
387
|
// The role is worked out first, because it narrows a name search too.
|
|
388
|
-
// Given both, only the name used to be searched, and the result still
|
|
389
|
-
// said the members found held the role.
|
|
390
388
|
let wantedRole;
|
|
391
389
|
if (role) {
|
|
392
390
|
const roles = await getRoles(rest, guildId);
|
package/dist/tools/realtime.js
CHANGED
|
@@ -7,7 +7,7 @@ import { ok, fail } from "../envelope.js";
|
|
|
7
7
|
import { enter, guarded, guildParam, resolveChannel } from "./common.js";
|
|
8
8
|
// Real-time event subscriptions over the gateway connection. Delivery is
|
|
9
9
|
// buffered: subscribe, let things happen, then poll get_recent_events.
|
|
10
|
-
// That works in every MCP client
|
|
10
|
+
// That works in every MCP client.
|
|
11
11
|
const TYPE_NAMES = Object.keys(SUBSCRIBABLE_TYPES);
|
|
12
12
|
// A ceiling on concurrent subscriptions, so a runaway caller cannot grow
|
|
13
13
|
// unbounded buffers. Each subscription already caps its own buffer.
|
package/dist/tools/roster.js
CHANGED
|
@@ -6,6 +6,7 @@ import { chooseSharedBot } from "../discord/botRouting.js";
|
|
|
6
6
|
import { quoted } from "../discord/names.js";
|
|
7
7
|
import { resolveOne } from "../discord/resolve.js";
|
|
8
8
|
import { ok, fail } from "../envelope.js";
|
|
9
|
+
import { settingSource } from "../settings.js";
|
|
9
10
|
import { enter, guarded, guildParam, memberDisplayName } from "./common.js";
|
|
10
11
|
// Roster reads: the servers the bot is in, a paged member list, and the
|
|
11
12
|
// members holding a role. search_members covers name and filter search;
|
|
@@ -45,7 +46,11 @@ export function registerRosterTools(server, config) {
|
|
|
45
46
|
};
|
|
46
47
|
}
|
|
47
48
|
}));
|
|
48
|
-
|
|
49
|
+
// Servers outside DISCORD_MCP_ALLOWED_SERVERS are left out: the tools
|
|
50
|
+
// refuse them, so listing them would only invite calls that fail.
|
|
51
|
+
const allowed = config.allowedServers;
|
|
52
|
+
const outsideIds = new Set(allowed ? perBot.flatMap(({ guilds }) => guilds.filter((g) => !allowed.has(g.id)).map((g) => g.id)) : []);
|
|
53
|
+
const servers = perBot.flatMap(({ bot, guilds }) => guilds.filter((g) => !outsideIds.has(g.id)).map((g) => ({
|
|
49
54
|
id: g.id,
|
|
50
55
|
name: g.name,
|
|
51
56
|
members_approximate: g.approximate_member_count ?? null,
|
|
@@ -91,6 +96,10 @@ export function registerRosterTools(server, config) {
|
|
|
91
96
|
? ` ${unreachable.length} unreachable (${unreachable.join(", ")}); check them with run_setup_check.`
|
|
92
97
|
: "");
|
|
93
98
|
}
|
|
99
|
+
if (outsideIds.size > 0) {
|
|
100
|
+
sharedNotes.push(`${outsideIds.size} more server(s) your bots are in are not listed: ` +
|
|
101
|
+
`this install may act only in the servers in ${settingSource("ALLOWED_SERVERS")}.`);
|
|
102
|
+
}
|
|
94
103
|
return ok(summary, {
|
|
95
104
|
bots: config.bots.map((b) => ({
|
|
96
105
|
name: b.name,
|
|
@@ -99,6 +108,7 @@ export function registerRosterTools(server, config) {
|
|
|
99
108
|
})),
|
|
100
109
|
servers: listed,
|
|
101
110
|
...(unreachable.length ? { unreachable } : {}),
|
|
111
|
+
...(outsideIds.size ? { not_allowed_here: outsideIds.size } : {}),
|
|
102
112
|
}, sharedNotes);
|
|
103
113
|
}));
|
|
104
114
|
server.registerTool("list_members", {
|
|
@@ -156,8 +166,7 @@ export function registerRosterTools(server, config) {
|
|
|
156
166
|
// Everyone holds @everyone, and members do not list it among their roles.
|
|
157
167
|
const everyone = roleId === guildId;
|
|
158
168
|
// How many hold it, from Discord's own count. The number of holders
|
|
159
|
-
// found while looking for enough to list is not that: it stops early
|
|
160
|
-
// and it used to be reported as the total.
|
|
169
|
+
// found while looking for enough to list is not that: it stops early.
|
|
161
170
|
let total;
|
|
162
171
|
if (!everyone) {
|
|
163
172
|
try {
|
package/dist/tools/settings.js
CHANGED
|
@@ -160,8 +160,8 @@ export function registerSettingsTools(server, config) {
|
|
|
160
160
|
}
|
|
161
161
|
// Discord requires these three of a Community server, so enabling
|
|
162
162
|
// it sets them. A different value passed in the same call cannot
|
|
163
|
-
// hold
|
|
164
|
-
//
|
|
163
|
+
// hold, so it is refused rather than overridden. And a setting
|
|
164
|
+
// changed only because Community needs it is
|
|
165
165
|
// named, since the caller did not ask for it.
|
|
166
166
|
if (explicit_media_filter !== undefined && explicit_media_filter !== "all_members") {
|
|
167
167
|
return fail("A Community server has to scan everyone's media, so explicit_media_filter can only be " +
|
package/dist/tools/write.js
CHANGED
|
@@ -18,7 +18,7 @@ import { sameOverwriteList } from "../builder/categorySync.js";
|
|
|
18
18
|
import { filesParam, prepareFiles, unreferencedFiles } from "../discord/uploads.js";
|
|
19
19
|
import { channelSettingsBody, channelSettingsContext, channelSettingsFields, hasChannelSettings } from "./channelSettings.js";
|
|
20
20
|
import { roleAppearanceBody, roleAppearanceFields } from "./roleAppearance.js";
|
|
21
|
-
// Write tools
|
|
21
|
+
// Write tools. Everything here changes state on Discord,
|
|
22
22
|
// so every tool preflights the bot's actual permissions and explains what
|
|
23
23
|
// is missing instead of letting Discord answer with a bare 403. The one
|
|
24
24
|
// destructive tool here, delete_message, runs through the confirmation
|
|
@@ -413,7 +413,7 @@ export function registerWriteTools(server, config) {
|
|
|
413
413
|
// Start from the category's overwrites, the way Discord does for a
|
|
414
414
|
// channel created without any, and change only what was asked.
|
|
415
415
|
// Sending a fresh set replaces the category's, so a read-only
|
|
416
|
-
// channel in a private category
|
|
416
|
+
// channel in a private category would come out visible to
|
|
417
417
|
// everyone.
|
|
418
418
|
const change = {};
|
|
419
419
|
if ((private_to?.length ?? 0) > 0) {
|
package/dist/unknownArguments.js
CHANGED
|
@@ -2,19 +2,20 @@ import { z } from "zod";
|
|
|
2
2
|
import { quoted } from "./discord/names.js";
|
|
3
3
|
import { fail, withWarning } from "./envelope.js";
|
|
4
4
|
import { setting } from "./settings.js";
|
|
5
|
-
// A tool's input schema strips what it does not declare, so
|
|
6
|
-
// tool does not have
|
|
7
|
-
// it had never been passed. The worst case is
|
|
8
|
-
// and on the rest a call marked as a rehearsal
|
|
9
|
-
// one level down: a channel in a
|
|
10
|
-
// key a channel does not have,
|
|
5
|
+
// A tool's input schema strips what it does not declare, so without this
|
|
6
|
+
// check a parameter a tool does not have would vanish without a word, and
|
|
7
|
+
// the call would run as if it had never been passed. The worst case is
|
|
8
|
+
// dry_run: some tools take it, and on the rest a call marked as a rehearsal
|
|
9
|
+
// would run for real. The same goes one level down: a channel in a
|
|
10
|
+
// blueprint written with private: true, a key a channel does not have,
|
|
11
|
+
// would be built for everyone to see.
|
|
11
12
|
//
|
|
12
13
|
// The check sits between the SDK and every tool (see buildServer). A tool
|
|
13
14
|
// that changes something refuses the call. A tool that only reads answers,
|
|
14
15
|
// and says what it ignored.
|
|
15
16
|
// Keys some hosts add to every tool call on their own. n8n's AI Agent sends
|
|
16
17
|
// these four with each call; they say nothing about what the tool should
|
|
17
|
-
// do, so they are dropped
|
|
18
|
+
// do, so they are dropped.
|
|
18
19
|
const HOST_KEYS = new Set(["sessionId", "action", "chatInput", "toolCallId"]);
|
|
19
20
|
// Tools marked read-only that refuse all the same, because what they hand
|
|
20
21
|
// back is run by another tool. plan_server_build changes nothing in
|
package/dist/updateCheck.js
CHANGED
|
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { PACKAGE_NAME } from "./identity.js";
|
|
4
4
|
import { setting } from "./settings.js";
|
|
5
|
+
import { BUNDLE_SETTINGS, packagedAs } from "./packaging.js";
|
|
5
6
|
// Telling people a newer version exists.
|
|
6
7
|
//
|
|
7
8
|
// A server like this is installed once and then runs for months. Nothing
|
|
@@ -107,11 +108,25 @@ export async function newerVersion(opts) {
|
|
|
107
108
|
}
|
|
108
109
|
export const UPDATE_COMMAND = `npx ${PACKAGE_NAME}@latest init`;
|
|
109
110
|
export const RELEASES_URL = "https://github.com/OrygnsCode/discord-mcp/releases";
|
|
111
|
+
export const BUNDLE_URL = `${RELEASES_URL}/latest/download/discord-mcp.mcpb`;
|
|
112
|
+
// Whether this copy asks for a newer version at all: an installed copy does.
|
|
113
|
+
// The Claude Desktop bundle runs outside node_modules but is an install like
|
|
114
|
+
// any other, and it never updates itself, so it asks too. The Docker image
|
|
115
|
+
// does not: its version is whatever image was deployed.
|
|
116
|
+
export function checksForUpdates(env = process.env, installed) {
|
|
117
|
+
return installed || packagedAs(env) === "mcpb";
|
|
118
|
+
}
|
|
119
|
+
// How this copy is updated. The Claude Desktop bundle does not update
|
|
120
|
+
// itself and has no npx to run: the new bundle is opened over the old one.
|
|
121
|
+
export function updateSteps(env = process.env) {
|
|
122
|
+
return packagedAs(env) === "mcpb"
|
|
123
|
+
? `downloads the new bundle (${BUNDLE_URL}) and opens it in Claude Desktop, or drags it onto ${BUNDLE_SETTINGS.replace(/ > Discord MCP$/, "")}`
|
|
124
|
+
: `runs \`${UPDATE_COMMAND}\`, chooses "Re-register with your AI client", and restarts the AI app`;
|
|
125
|
+
}
|
|
110
126
|
// One line, written as information for the AI to pass on, not as an order
|
|
111
|
-
// to it: what is out,
|
|
112
|
-
export function updateNotice(latest, current) {
|
|
113
|
-
return (`discord-mcp ${latest} is available; this is ${current}. To update, the person who set this up
|
|
114
|
-
`\`${UPDATE_COMMAND}\`, chooses "Re-register with your AI client", and restarts the AI app. ` +
|
|
127
|
+
// to it: what is out, how to update, and where the changes are listed.
|
|
128
|
+
export function updateNotice(latest, current, env = process.env) {
|
|
129
|
+
return (`discord-mcp ${latest} is available; this is ${current}. To update, the person who set this up ${updateSteps(env)}. ` +
|
|
115
130
|
`What changed: ${RELEASES_URL}`);
|
|
116
131
|
}
|
|
117
132
|
// ---- the running process ----
|
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { Routes } from "discord-api-types/v10";
|
|
5
|
+
import { VERSION } from "./config.js";
|
|
6
|
+
import { IS_INSTALLED, PACKAGE_ROOT } from "./home.js";
|
|
7
|
+
import { inNpxCache } from "./install.js";
|
|
8
|
+
import { packagedAs } from "./packaging.js";
|
|
9
|
+
import { getRestForToken } from "./discord/client.js";
|
|
10
|
+
import { ERROR_CLASSES, GATE_EVENTS, currentAppName, flush, startCounting, usageDir, usageSwitch, utcDay, } from "./usageStats.js";
|
|
11
|
+
// The daily usage report. At most once per UTC day per install (the
|
|
12
|
+
// settings folder is the install), on the first day's call that reached
|
|
13
|
+
// Discord, it sends what the install looks like and the counts of the days
|
|
14
|
+
// before, then stays quiet until the next day. See docs/privacy.md for the
|
|
15
|
+
// fields; every value is a number band or one of a fixed list.
|
|
16
|
+
//
|
|
17
|
+
// Several copies of the server can share one install (an app per window,
|
|
18
|
+
// two AI apps), so one lock file decides which of them sends, and the state
|
|
19
|
+
// file says a day was sent only once the receiver answered. A day's report
|
|
20
|
+
// carries a random number, reused if it has to be sent again; the receiver
|
|
21
|
+
// counts each number once and forgets it after two days, so a retry never
|
|
22
|
+
// counts twice and nothing links one day's report to another's.
|
|
23
|
+
export const REPORT_BASE = "https://telemetry.orygn.tech";
|
|
24
|
+
// The receiver's paths on that host.
|
|
25
|
+
export const REPORT_PATH = "/discord-mcp/v1";
|
|
26
|
+
export const SCHEMA = 1;
|
|
27
|
+
const SEND_TIMEOUT_MS = 3_000;
|
|
28
|
+
const LOCK_STALE_MS = 60_000;
|
|
29
|
+
// A day's counts wait this long after a process last wrote them, so one
|
|
30
|
+
// still finishing its write at midnight is not sent half done.
|
|
31
|
+
const SETTLE_MS = 60_000;
|
|
32
|
+
const MAX_DAYS = 7;
|
|
33
|
+
// The receiver takes reports up to 64 KB. A week of heavy use, every tool
|
|
34
|
+
// every day, comes near that, so the oldest days are left out until the
|
|
35
|
+
// report fits.
|
|
36
|
+
export const MAX_REPORT_BYTES = 60_000;
|
|
37
|
+
// --- bands ---
|
|
38
|
+
export function countBand(n) {
|
|
39
|
+
return n >= 100 ? "100+" : n >= 10 ? "10-99" : "1-9";
|
|
40
|
+
}
|
|
41
|
+
export function botsBand(n) {
|
|
42
|
+
return n >= 4 ? "4+" : n >= 2 ? "2-3" : "1";
|
|
43
|
+
}
|
|
44
|
+
export function serversBand(n) {
|
|
45
|
+
return n === 0 ? "0" : n === 1 ? "1" : n <= 5 ? "2-5" : n <= 20 ? "6-20" : "21+";
|
|
46
|
+
}
|
|
47
|
+
export function sizeBand(members) {
|
|
48
|
+
return members >= 5000 ? "5k+" : members >= 500 ? "500-5k" : members >= 50 ? "50-500" : "<50";
|
|
49
|
+
}
|
|
50
|
+
export function ageBand(days) {
|
|
51
|
+
return days <= 0 ? "0" : days <= 7 ? "1-7" : days <= 30 ? "8-30" : days <= 90 ? "31-90" : "90+";
|
|
52
|
+
}
|
|
53
|
+
// --- where and how it runs ---
|
|
54
|
+
export function osName(platform = process.platform) {
|
|
55
|
+
return platform === "win32" ? "windows" : platform === "darwin" ? "macos" : platform === "linux" ? "linux" : "other";
|
|
56
|
+
}
|
|
57
|
+
// How this copy was installed. The Docker image and the Claude Desktop
|
|
58
|
+
// bundle say so themselves (DISCORD_MCP_PACKAGING); the rest is read from
|
|
59
|
+
// where the package sits.
|
|
60
|
+
export function installKind(env = process.env, root = PACKAGE_ROOT, installed = IS_INSTALLED) {
|
|
61
|
+
const packaged = packagedAs(env);
|
|
62
|
+
if (packaged)
|
|
63
|
+
return packaged;
|
|
64
|
+
if (!installed)
|
|
65
|
+
return "source";
|
|
66
|
+
if (inNpxCache(root))
|
|
67
|
+
return "npx";
|
|
68
|
+
// The wizard's own copy: <home>/app/<version>/node_modules/...
|
|
69
|
+
if (/[\\/]app[\\/]\d+\.\d+\.\d+[^\\/]*[\\/]node_modules[\\/]/.test(root))
|
|
70
|
+
return "wizard";
|
|
71
|
+
// npm's global folder is node_modules under lib (Unix) or npm (Windows).
|
|
72
|
+
if (/[\\/](?:lib|npm)[\\/]node_modules[\\/]/.test(root))
|
|
73
|
+
return "global";
|
|
74
|
+
return "other";
|
|
75
|
+
}
|
|
76
|
+
export function runContext(env = process.env, fileExists = existsSync) {
|
|
77
|
+
if (packagedAs(env) === "docker")
|
|
78
|
+
return "container";
|
|
79
|
+
if (env.KUBERNETES_SERVICE_HOST || fileExists("/.dockerenv") || fileExists("/run/.containerenv"))
|
|
80
|
+
return "container";
|
|
81
|
+
return "default";
|
|
82
|
+
}
|
|
83
|
+
// --- the days ---
|
|
84
|
+
function isoWeekStart(day) {
|
|
85
|
+
const d = new Date(`${day}T00:00:00Z`);
|
|
86
|
+
const back = (d.getUTCDay() + 6) % 7;
|
|
87
|
+
return utcDay(new Date(d.getTime() - back * 86_400_000));
|
|
88
|
+
}
|
|
89
|
+
function daysBetween(from, to) {
|
|
90
|
+
return Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 86_400_000);
|
|
91
|
+
}
|
|
92
|
+
// Whether today is this install's first active day of its week, month, and
|
|
93
|
+
// ever, from the days before it. Worked out from the days before today
|
|
94
|
+
// only, so a report sent again later the same day says the same.
|
|
95
|
+
export function firstFlags(active, day, firstSeen) {
|
|
96
|
+
const earlier = active.filter((d) => d < day);
|
|
97
|
+
return {
|
|
98
|
+
week: !earlier.some((d) => isoWeekStart(d) === isoWeekStart(day)),
|
|
99
|
+
month: !earlier.some((d) => d.slice(0, 7) === day.slice(0, 7)),
|
|
100
|
+
ever: earlier.length === 0 && (firstSeen === undefined || firstSeen === day),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
// The finished days' counts, added up across every process's file. A day
|
|
104
|
+
// with a file written in the last minute waits for the next report.
|
|
105
|
+
export function collectDays(dir, today, now = Date.now()) {
|
|
106
|
+
const byDay = new Map();
|
|
107
|
+
let names = [];
|
|
108
|
+
try {
|
|
109
|
+
names = readdirSync(dir);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return { days: [], files: [] };
|
|
113
|
+
}
|
|
114
|
+
for (const name of names) {
|
|
115
|
+
const m = name.match(/^day-(\d{4}-\d{2}-\d{2})-[\w-]+\.json$/);
|
|
116
|
+
if (!m || m[1] >= today)
|
|
117
|
+
continue;
|
|
118
|
+
const path = join(dir, name);
|
|
119
|
+
let tally;
|
|
120
|
+
let mtime;
|
|
121
|
+
try {
|
|
122
|
+
tally = JSON.parse(readFileSync(path, "utf8"));
|
|
123
|
+
mtime = statSync(path).mtimeMs;
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const entry = byDay.get(m[1]) ?? { tally: { tools: {}, gate: {}, errors: {}, apps: [] }, files: [], fresh: false };
|
|
129
|
+
for (const [tool, n] of Object.entries(tally.tools ?? {}))
|
|
130
|
+
entry.tally.tools[tool] = (entry.tally.tools[tool] ?? 0) + (Number(n) || 0);
|
|
131
|
+
for (const [k, n] of Object.entries(tally.gate ?? {})) {
|
|
132
|
+
const key = k;
|
|
133
|
+
entry.tally.gate[key] = (entry.tally.gate[key] ?? 0) + (Number(n) || 0);
|
|
134
|
+
}
|
|
135
|
+
for (const [k, n] of Object.entries(tally.errors ?? {})) {
|
|
136
|
+
const key = k;
|
|
137
|
+
entry.tally.errors[key] = (entry.tally.errors[key] ?? 0) + (Number(n) || 0);
|
|
138
|
+
}
|
|
139
|
+
for (const app of tally.apps ?? [])
|
|
140
|
+
if (!entry.tally.apps.includes(app))
|
|
141
|
+
entry.tally.apps.push(app);
|
|
142
|
+
entry.files.push(path);
|
|
143
|
+
if (now - mtime < SETTLE_MS)
|
|
144
|
+
entry.fresh = true;
|
|
145
|
+
byDay.set(m[1], entry);
|
|
146
|
+
}
|
|
147
|
+
const ready = [...byDay.entries()].filter(([, e]) => !e.fresh).sort(([a], [b]) => (a < b ? 1 : -1)).slice(0, MAX_DAYS);
|
|
148
|
+
return {
|
|
149
|
+
days: ready.map(([d, e]) => ({
|
|
150
|
+
d,
|
|
151
|
+
tools: banded(e.tally.tools),
|
|
152
|
+
gate: banded(Object.fromEntries(GATE_EVENTS.filter((k) => e.tally.gate[k]).map((k) => [k, e.tally.gate[k]]))),
|
|
153
|
+
errors: banded(Object.fromEntries(ERROR_CLASSES.filter((k) => e.tally.errors[k]).map((k) => [k, e.tally.errors[k]]))),
|
|
154
|
+
apps: e.tally.apps.slice(0, 10),
|
|
155
|
+
})),
|
|
156
|
+
files: ready.flatMap(([, e]) => e.files),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function banded(counts) {
|
|
160
|
+
const out = {};
|
|
161
|
+
for (const [k, n] of Object.entries(counts))
|
|
162
|
+
if (n > 0 && /^[a-z][a-z0-9_-]{0,47}$/.test(k))
|
|
163
|
+
out[k] = countBand(n);
|
|
164
|
+
return out;
|
|
165
|
+
}
|
|
166
|
+
// --- state and the lock ---
|
|
167
|
+
function readState(dir) {
|
|
168
|
+
try {
|
|
169
|
+
const s = JSON.parse(readFileSync(join(dir, "state.json"), "utf8"));
|
|
170
|
+
return { ...s, active: Array.isArray(s.active) ? s.active.filter((d) => /^\d{4}-\d{2}-\d{2}$/.test(d)) : [] };
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return { active: [] };
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function writeState(dir, state) {
|
|
177
|
+
const temp = join(dir, `state.json.${process.pid}.tmp`);
|
|
178
|
+
writeFileSync(temp, JSON.stringify(state));
|
|
179
|
+
renameSync(temp, join(dir, "state.json"));
|
|
180
|
+
}
|
|
181
|
+
// Made with exclusive create, so of several processes trying at once one
|
|
182
|
+
// gets it. A lock older than a minute belongs to a process that died.
|
|
183
|
+
function takeLock(dir, now) {
|
|
184
|
+
const path = join(dir, "send.lock");
|
|
185
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
186
|
+
try {
|
|
187
|
+
const fd = openSync(path, "wx");
|
|
188
|
+
writeSync(fd, String(process.pid));
|
|
189
|
+
closeSync(fd);
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
try {
|
|
194
|
+
if (now - statSync(path).mtimeMs > LOCK_STALE_MS) {
|
|
195
|
+
rmSync(path, { force: true });
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
function releaseLock(dir) {
|
|
208
|
+
rmSync(join(dir, "send.lock"), { force: true });
|
|
209
|
+
}
|
|
210
|
+
// After a failed send: 15 minutes, doubling, at most 6 hours.
|
|
211
|
+
export function backoffMs(failures) {
|
|
212
|
+
return Math.min(15 * 60_000 * 2 ** Math.max(0, failures - 1), 6 * 3_600_000);
|
|
213
|
+
}
|
|
214
|
+
const realPost = async (url, body) => {
|
|
215
|
+
try {
|
|
216
|
+
const res = await fetch(url, {
|
|
217
|
+
method: "POST",
|
|
218
|
+
headers: { "content-type": "application/json", "user-agent": `discord-mcp/${VERSION}` },
|
|
219
|
+
body,
|
|
220
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
|
221
|
+
redirect: "error",
|
|
222
|
+
});
|
|
223
|
+
return res.status;
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
return 0;
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
// What a status means for the report: taken; refused for what it is, which
|
|
230
|
+
// sending it again would not change; or not taken this time.
|
|
231
|
+
export function sendOutcome(status) {
|
|
232
|
+
if (status >= 200 && status < 300)
|
|
233
|
+
return "sent";
|
|
234
|
+
if (status >= 400 && status < 500 && status !== 408 && status !== 429)
|
|
235
|
+
return "rejected";
|
|
236
|
+
return "failed";
|
|
237
|
+
}
|
|
238
|
+
// The report as sent, without the oldest days while it is too large.
|
|
239
|
+
export function fitReport(report) {
|
|
240
|
+
let body = JSON.stringify(report);
|
|
241
|
+
while (body.length > MAX_REPORT_BYTES && report.days.length > 0) {
|
|
242
|
+
report.days = report.days.slice(0, -1);
|
|
243
|
+
body = JSON.stringify(report);
|
|
244
|
+
}
|
|
245
|
+
return body;
|
|
246
|
+
}
|
|
247
|
+
// The servers a report counts, from each bot's list: every server once, and
|
|
248
|
+
// only those this install may act in (DISCORD_MCP_ALLOWED_SERVERS).
|
|
249
|
+
export function countServers(lists, allowed) {
|
|
250
|
+
const ids = new Set();
|
|
251
|
+
let largest = 0;
|
|
252
|
+
for (const guilds of lists) {
|
|
253
|
+
for (const g of guilds) {
|
|
254
|
+
if (allowed && !allowed.has(g.id))
|
|
255
|
+
continue;
|
|
256
|
+
ids.add(g.id);
|
|
257
|
+
largest = Math.max(largest, g.approximate_member_count ?? 0);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return { servers: ids.size, largest };
|
|
261
|
+
}
|
|
262
|
+
const realGuildCounts = async (config) => {
|
|
263
|
+
try {
|
|
264
|
+
const lists = [];
|
|
265
|
+
for (const bot of config.bots) {
|
|
266
|
+
lists.push((await getRestForToken(bot.token).get(Routes.userGuilds(), {
|
|
267
|
+
query: new URLSearchParams({ with_counts: "true" }),
|
|
268
|
+
})));
|
|
269
|
+
}
|
|
270
|
+
return countServers(lists, config.allowedServers);
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
return undefined;
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
let deps = { post: realPost, guildCounts: realGuildCounts, env: process.env };
|
|
277
|
+
// Where reports go. DISCORD_MCP_TELEMETRY_URL points them at another
|
|
278
|
+
// receiver, such as one run locally to test against.
|
|
279
|
+
function endpoint(path) {
|
|
280
|
+
const override = deps.env.DISCORD_MCP_TELEMETRY_URL?.trim().replace(/\/+$/, "");
|
|
281
|
+
return (override && /^https?:\/\/[^\s]+$/.test(override) ? override : REPORT_BASE) + path;
|
|
282
|
+
}
|
|
283
|
+
let config;
|
|
284
|
+
let sending = false;
|
|
285
|
+
let sentDay;
|
|
286
|
+
let retryAfter = 0;
|
|
287
|
+
// Turns the report on for this process, when usage stats are on and a bot
|
|
288
|
+
// is configured. Counting starts with it.
|
|
289
|
+
export function startUsageReport(cfg) {
|
|
290
|
+
config = cfg;
|
|
291
|
+
startCounting({ hasBot: cfg.bots.length > 0, onActiveDay: () => void sendIfDue() });
|
|
292
|
+
}
|
|
293
|
+
// Sends today's report if it has not gone out yet. Never throws, never
|
|
294
|
+
// writes to stdout, never holds up a tool: it runs after the result is out.
|
|
295
|
+
export async function sendIfDue(now = new Date()) {
|
|
296
|
+
if (!config || sending || !usageSwitch(deps.env).on)
|
|
297
|
+
return "skipped";
|
|
298
|
+
const day = utcDay(now);
|
|
299
|
+
if (sentDay === day || now.getTime() < retryAfter)
|
|
300
|
+
return "skipped";
|
|
301
|
+
sending = true;
|
|
302
|
+
const dir = usageDir();
|
|
303
|
+
try {
|
|
304
|
+
mkdirSync(dir, { recursive: true });
|
|
305
|
+
const before = readState(dir);
|
|
306
|
+
if (before.sent_day === day) {
|
|
307
|
+
sentDay = day;
|
|
308
|
+
return "skipped";
|
|
309
|
+
}
|
|
310
|
+
if (before.next_try_at && Date.parse(before.next_try_at) > now.getTime()) {
|
|
311
|
+
retryAfter = Date.parse(before.next_try_at);
|
|
312
|
+
return "skipped";
|
|
313
|
+
}
|
|
314
|
+
if (!takeLock(dir, now.getTime()))
|
|
315
|
+
return "skipped";
|
|
316
|
+
try {
|
|
317
|
+
// Read again under the lock: another process may have just sent.
|
|
318
|
+
const state = readState(dir);
|
|
319
|
+
if (state.sent_day === day) {
|
|
320
|
+
sentDay = day;
|
|
321
|
+
return "skipped";
|
|
322
|
+
}
|
|
323
|
+
if (state.nonce?.day !== day)
|
|
324
|
+
state.nonce = { day, value: randomBytes(16).toString("hex") };
|
|
325
|
+
if (!state.first_seen)
|
|
326
|
+
state.first_seen = day;
|
|
327
|
+
const first = firstFlags(state.active, day, state.first_seen);
|
|
328
|
+
if (!state.active.includes(day))
|
|
329
|
+
state.active = [...state.active.filter((d) => d < day), day].slice(-40);
|
|
330
|
+
// Saved before sending, so a retry reuses the same number and flags.
|
|
331
|
+
writeState(dir, state);
|
|
332
|
+
flush();
|
|
333
|
+
const { days, files } = collectDays(dir, day, now.getTime());
|
|
334
|
+
const counts = await deps.guildCounts(config);
|
|
335
|
+
const report = {
|
|
336
|
+
s: SCHEMA,
|
|
337
|
+
day,
|
|
338
|
+
nonce: state.nonce.value,
|
|
339
|
+
v: VERSION,
|
|
340
|
+
os: osName(),
|
|
341
|
+
app: currentAppName(),
|
|
342
|
+
install: installKind(deps.env),
|
|
343
|
+
ctx: runContext(deps.env),
|
|
344
|
+
bots: botsBand(config.bots.length),
|
|
345
|
+
...(counts ? { servers: serversBand(counts.servers), largest: sizeBand(counts.largest) } : {}),
|
|
346
|
+
age: ageBand(daysBetween(state.first_seen, day)),
|
|
347
|
+
first,
|
|
348
|
+
days,
|
|
349
|
+
};
|
|
350
|
+
const outcome = sendOutcome(await deps.post(endpoint(`${REPORT_PATH}/ping`), fitReport(report)));
|
|
351
|
+
if (outcome === "failed") {
|
|
352
|
+
state.failures = (state.failures ?? 0) + 1;
|
|
353
|
+
retryAfter = now.getTime() + backoffMs(state.failures);
|
|
354
|
+
state.next_try_at = new Date(retryAfter).toISOString();
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
// Taken, or refused for good: either way this day is done, and the
|
|
358
|
+
// counts it carried go, so a report the receiver will never take
|
|
359
|
+
// cannot be retried for ever.
|
|
360
|
+
state.sent_day = day;
|
|
361
|
+
delete state.failures;
|
|
362
|
+
delete state.next_try_at;
|
|
363
|
+
for (const f of files)
|
|
364
|
+
rmSync(f, { force: true });
|
|
365
|
+
sentDay = day;
|
|
366
|
+
}
|
|
367
|
+
writeState(dir, state);
|
|
368
|
+
return outcome;
|
|
369
|
+
}
|
|
370
|
+
finally {
|
|
371
|
+
releaseLock(dir);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
return "failed";
|
|
376
|
+
}
|
|
377
|
+
finally {
|
|
378
|
+
sending = false;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
// --- the setup wizard ---
|
|
382
|
+
export const SETUP_FLOWS = ["fresh", "add_bot", "reregister", "upgrade"];
|
|
383
|
+
export const SETUP_OUTCOMES = ["completed", "unfinished", "cancelled", "failed"];
|
|
384
|
+
// One report when the wizard ends: which path it took, how it ended, and
|
|
385
|
+
// which app it set up. Waits at most the send timeout.
|
|
386
|
+
export async function sendSetupEvent(event) {
|
|
387
|
+
if (!usageSwitch(deps.env).on)
|
|
388
|
+
return false;
|
|
389
|
+
const body = {
|
|
390
|
+
s: SCHEMA,
|
|
391
|
+
kind: "setup",
|
|
392
|
+
day: utcDay(),
|
|
393
|
+
nonce: randomBytes(16).toString("hex"),
|
|
394
|
+
v: VERSION,
|
|
395
|
+
os: osName(),
|
|
396
|
+
install: installKind(deps.env),
|
|
397
|
+
flow: event.flow,
|
|
398
|
+
outcome: event.outcome,
|
|
399
|
+
apps: [...new Set(event.apps)].slice(0, 5),
|
|
400
|
+
};
|
|
401
|
+
return sendOutcome(await deps.post(endpoint(`${REPORT_PATH}/setup`), JSON.stringify(body))) === "sent";
|
|
402
|
+
}
|
|
403
|
+
// For tests: swap what sends and what counts servers, and reset the
|
|
404
|
+
// in-process memory of what was sent.
|
|
405
|
+
export const __testing = {
|
|
406
|
+
use(next, cfg) {
|
|
407
|
+
deps = { ...deps, ...next };
|
|
408
|
+
if (cfg)
|
|
409
|
+
config = cfg;
|
|
410
|
+
sentDay = undefined;
|
|
411
|
+
retryAfter = 0;
|
|
412
|
+
sending = false;
|
|
413
|
+
},
|
|
414
|
+
reset() {
|
|
415
|
+
deps = { post: realPost, guildCounts: realGuildCounts, env: process.env };
|
|
416
|
+
config = undefined;
|
|
417
|
+
sentDay = undefined;
|
|
418
|
+
retryAfter = 0;
|
|
419
|
+
sending = false;
|
|
420
|
+
},
|
|
421
|
+
};
|