-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.ts
More file actions
460 lines (405 loc) · 15.9 KB
/
Copy pathmain.ts
File metadata and controls
460 lines (405 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/**
* Discord MCP Server - Main Entry Point
*
* MCP server for Discord bot integration with message indexing
* and AI agent commands.
*/
import { serve } from "@decocms/mcps-shared/serve";
import { withRuntime } from "@decocms/runtime";
import {
initializeDiscordClient,
getDiscordClient,
shutdownDiscordClient,
} from "./discord/client.ts";
import { setDatabaseEnv } from "../shared/db.ts";
import { updateEnv, getCurrentEnv, ensureBotRunning } from "./bot-manager.ts";
import { tools } from "./tools/index.ts";
import { type Env, type Registry, StateSchema } from "./types/env.ts";
import { logger, HyperDXLogger } from "./lib/logger.ts";
import { app as webhookRouter } from "./router.ts";
import {
setDiscordConfig,
getDiscordConfig,
type DiscordConfig,
} from "./lib/config-cache.ts";
export { StateSchema };
// ============================================================================
// STARTUP DEBUGGING
// ============================================================================
// Generate unique instance ID to detect multiple instances running
const INSTANCE_ID = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
console.log("=".repeat(80));
console.log("[STARTUP] Discord MCP Server initializing...");
console.log(`[STARTUP] 🆔 Instance ID: ${INSTANCE_ID}`);
console.log(`[STARTUP] Node.js version: ${process.version}`);
console.log(`[STARTUP] Bun version: ${Bun.version}`);
console.log(`[STARTUP] NODE_ENV: ${process.env.NODE_ENV || "not set"}`);
console.log(`[STARTUP] PORT: ${process.env.PORT || "not set"}`);
console.log(`[STARTUP] Working directory: ${process.cwd()}`);
console.log("=".repeat(80));
// Track Discord client state
let discordInitialized = false;
// Auto-restart cron interval (1 hour)
const AUTO_RESTART_INTERVAL_MS = 60 * 60 * 1000;
let autoRestartInterval: ReturnType<typeof setInterval> | null = null;
const runtime = withRuntime<Env, typeof StateSchema, Registry>({
events: {
handlers: {
SELF: {
events: ["discord.*"],
handler: async ({ events }) => {
try {
for (const event of events) {
console.log(`[SELF] Event: ${event.type}`);
}
return { success: true };
} catch (error) {
console.error(`[SELF] Error:`, error);
return { success: false };
}
},
},
EVENT_BUS: {
handler: async ({ events }) => {
try {
for (const event of events) {
console.log(`[EVENT_BUS] Event: ${event.type}`);
}
return { success: true };
} catch (error) {
console.error(`[EVENT_BUS] Error:`, error);
return { success: false };
}
},
events: ["discord.*"],
},
},
},
configuration: {
onChange: async (env) => {
const traceId = HyperDXLogger.generateTraceId();
logger.info("Configuration changed", {
trace_id: traceId,
organizationId: env.MESH_REQUEST_CONTEXT?.organizationId,
connectionId: env.MESH_REQUEST_CONTEXT?.connectionId,
});
// Update global env for Discord bot handlers
updateEnv(env);
// Set database env for shared module
setDatabaseEnv(env);
// Get configuration from state
const state = env.MESH_REQUEST_CONTEXT?.state;
const meshUrl = env.MESH_REQUEST_CONTEXT?.meshUrl;
const organizationId = env.MESH_REQUEST_CONTEXT?.organizationId;
const token = env.MESH_REQUEST_CONTEXT?.token;
// Configure HyperDX logger if API key is provided
if (state?.HYPERDX_API_KEY) {
logger.setApiKey(state.HYPERDX_API_KEY);
logger.info("HyperDX logger configured", {
trace_id: traceId,
organizationId,
});
}
// Create tables first, then indexes
// Database tables are managed via Supabase - no need to ensure here
console.log("[Setup] Skipping database initialization (using Supabase)");
logger.info("Database tables ready", {
trace_id: traceId,
organizationId,
});
// Configure LLM
const agent = state?.AGENT;
const languageModel = state?.LANGUAGE_MODEL;
// Extract values - connectionId comes from LANGUAGE_MODEL
const modelProviderId: string | undefined =
typeof languageModel?.value?.connectionId === "string"
? languageModel.value.connectionId
: undefined;
const agentId: string | undefined =
typeof agent?.value === "string" ? agent.value : undefined;
const agentMode = state?.AGENT_MODE ?? "smart_tool_selection";
const modelId = languageModel?.value?.id;
// Get existing config to check for persistent API key
const currentConnectionId = env.MESH_REQUEST_CONTEXT?.connectionId;
const savedConfig = currentConnectionId
? await getDiscordConfig(currentConnectionId)
: null;
// Use API key if available (never expires), otherwise use session token (expires in 5 min)
const effectiveToken = savedConfig?.meshApiKey || token;
const isUsingApiKey = !!savedConfig?.meshApiKey;
// Configure LLM module (modelProviderId is optional)
if (effectiveToken && meshUrl && organizationId && languageModel) {
const { configureLLM, configureStreaming } = await import("./llm.ts");
configureLLM({
meshUrl,
organizationId,
token: effectiveToken,
modelProviderId,
modelId,
agentId,
agentMode,
});
console.log(
`[CONFIG] LLM token: ${isUsingApiKey ? "🔑 API Key (persistent)" : "⏱️ Session token (expires in 5 min)"}`,
);
if (!isUsingApiKey) {
console.warn(
"[CONFIG] ⚠️ Using session token which expires in 5 min. Generate an API key using DISCORD_GENERATE_API_KEY tool for persistent LLM access.",
);
}
// Configure streaming (default: enabled)
const enableStreaming =
state?.RESPONSE_CONFIG?.ENABLE_STREAMING ?? true;
configureStreaming(enableStreaming);
console.log("[CONFIG] LLM configured:", {
modelProviderId,
modelId,
agentId: agentId || "not set",
streaming: enableStreaming,
});
}
// ======================================================================
// Sync StateSchema fields to config-cache for webhook endpoint
// ======================================================================
const connectionId = env.MESH_REQUEST_CONTEXT?.connectionId;
const authorization = env.MESH_REQUEST_CONTEXT?.authorization;
const discordPublicKey = state?.DISCORD_PUBLIC_KEY;
const discordApplicationId = state?.DISCORD_APPLICATION_ID;
const authorizedGuildsStr = state?.AUTHORIZED_GUILDS;
const botOwnerId = state?.BOT_OWNER_ID;
const commandPrefix = state?.COMMAND_PREFIX || "!";
const superAdminsStr = state?.BOT_SUPER_ADMINS;
// Parse authorized guilds (comma-separated string to array)
const authorizedGuilds = authorizedGuildsStr
? authorizedGuildsStr
.split(",")
.map((g) => g.trim())
.filter(Boolean)
: [];
// Parse and set super admins (comma-separated string to array)
const superAdmins = superAdminsStr
? superAdminsStr
.split(",")
.map((id) => id.trim())
.filter(Boolean)
: [];
if (superAdmins.length > 0) {
const { setSuperAdmins } = await import(
"./discord/handlers/messageHandler.ts"
);
setSuperAdmins(superAdmins);
console.log(`[CONFIG] Super admins: ${superAdmins.length} configured`);
}
// If we have a connection ID, sync to config-cache (discordPublicKey is optional but needed for webhooks)
if (connectionId && organizationId && meshUrl) {
// Try to load existing config to preserve other fields
const existingConfig = await getDiscordConfig(connectionId);
// Extract bot token from authorization header (Bearer token)
let botToken = existingConfig?.botToken || "";
if (authorization) {
const authMatch = authorization.match(/^Bearer\s+(.+)$/i);
if (authMatch) {
botToken = authMatch[1];
}
}
const configToSave: DiscordConfig = {
// Preserve existing config fields
...(existingConfig || {}),
// Update with current values
connectionId,
organizationId,
meshUrl,
meshToken: token,
botToken,
discordPublicKey,
discordApplicationId,
authorizedGuilds,
ownerId: botOwnerId,
commandPrefix,
modelProviderId,
modelId,
agentId,
updatedAt: new Date().toISOString(),
};
await setDiscordConfig(configToSave);
console.log(
`[CONFIG] ✅ Synced StateSchema to config-cache for webhook endpoint`,
);
console.log(
`[CONFIG] Discord Public Key: ${discordPublicKey ? "✓ configured" : "✗ missing"}`,
);
console.log(
`[CONFIG] Application ID: ${discordApplicationId || "not set"}`,
);
console.log(
`[CONFIG] Authorized Guilds: ${authorizedGuilds.length > 0 ? authorizedGuilds.join(", ") : "all"}`,
);
}
// Auto-initialize Discord client when config is available
const hasAuth = !!env.MESH_REQUEST_CONTEXT?.authorization;
if (hasAuth) {
if (discordInitialized && getDiscordClient()?.isReady()) {
console.log("[CONFIG] ✅ Bot is running");
} else {
console.log("[CONFIG] ⚡ Auto-starting Discord bot...");
try {
const started = await ensureBotRunning(env);
if (started) {
discordInitialized = true;
console.log("[CONFIG] ✅ Bot auto-started successfully");
} else {
console.log(
"[CONFIG] ⚠️ Bot auto-start failed. Use DISCORD_BOT_START tool manually.",
);
}
} catch (error) {
console.error(
"[CONFIG] ❌ Bot auto-start error:",
error instanceof Error ? error.message : String(error),
);
}
}
} else {
logger.info(
"Discord Bot Token not configured - waiting for authorization",
{
trace_id: traceId,
organizationId,
},
);
}
},
scopes: ["EVENT_BUS::*", "CONNECTION::*", "*"],
state: StateSchema,
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
tools: tools as any,
prompts: [],
});
// Graceful shutdown handler - destroy Discord client when process exits
async function gracefulShutdown(signal: string) {
console.log(`\n[SHUTDOWN] Received ${signal}, shutting down...`);
try {
// Stop auto-restart cron
if (autoRestartInterval) {
console.log("[SHUTDOWN] Stopping auto-restart cron...");
clearInterval(autoRestartInterval);
autoRestartInterval = null;
}
const client = getDiscordClient();
if (client) {
console.log("[SHUTDOWN] Destroying Discord client...");
await shutdownDiscordClient();
console.log("[SHUTDOWN] Discord client destroyed ✓");
}
} catch (error) {
console.error("[SHUTDOWN] Error during shutdown:", error);
}
process.exit(0);
}
// Register shutdown handlers
process.on("SIGINT", () => gracefulShutdown("SIGINT"));
process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
process.on("beforeExit", () => gracefulShutdown("beforeExit"));
// Also handle uncaught exceptions to cleanup
process.on("uncaughtException", async (error) => {
console.error("[CRASH] Uncaught exception:", error);
await gracefulShutdown("uncaughtException");
});
// ============================================================================
// START HTTP SERVER FIRST (before any Discord initialization)
// ============================================================================
console.log("[SERVER] Starting HTTP server...");
console.log(
`[SERVER] PORT env variable: ${process.env.PORT || "not set (will use default)"}`,
);
/**
* Serve requests:
* - Webhook routes handled by webhookRouter (/discord/interactions, /health)
* - MCP requests handled by runtime
*/
try {
serve(async (req, env, ctx) => {
// Try webhook router first
const webhookResponse = await webhookRouter.fetch(req, env, ctx);
// If webhook router returned 404, fall back to MCP runtime
if (webhookResponse.status === 404) {
return runtime.fetch(req, env, ctx);
}
return webhookResponse;
});
console.log("[SERVER] ✅ serve() called successfully");
console.log("[SERVER] Webhook endpoint: /discord/interactions/:connectionId");
console.log("[SERVER] Health check: /health");
} catch (error) {
console.error("[SERVER] ❌ Failed to start server:", error);
throw error;
}
console.log(`
╔══════════════════════════════════════════════════════════╗
║ Discord MCP Server Started ║
╠══════════════════════════════════════════════════════════╣
║ Status: ✅ HTTP Server Ready ║
║ Discord Bot: Waiting for configuration... ║
╚══════════════════════════════════════════════════════════╝
`);
console.log(`
📡 MCP Server ready!
💡 The Discord bot will start when Mesh sends the configuration.
→ Open Mesh Dashboard and click on this MCP to trigger initialization.
→ Or use the tools in the dashboard.
⚠️ Press Ctrl+C to gracefully shutdown the Discord bot.
`);
// ============================================================================
// BOT INITIALIZATION
// ============================================================================
// Bot will be initialized via:
// 1. onChange configuration callback (when Mesh sends config)
// 2. DISCORD_BOT_START tool (manual start)
// ============================================================================
// Auto-Restart Cron Job (every 1 hour)
// ============================================================================
/**
* Check if the bot is running and restart if needed.
* Runs every hour to ensure the bot stays online.
*/
async function autoRestartCheck(): Promise<void> {
const client = getDiscordClient();
if (!client || !client.isReady()) {
console.log("[AUTO-RESTART] Bot is down, attempting restart...");
const env = getCurrentEnv();
if (!env) {
console.log("[AUTO-RESTART] No environment available, skipping restart");
return;
}
const hasAuth = !!env.MESH_REQUEST_CONTEXT?.authorization;
if (!hasAuth) {
console.log(
"[AUTO-RESTART] No authorization configured, skipping restart",
);
return;
}
try {
await initializeDiscordClient(env);
discordInitialized = true;
console.log("[AUTO-RESTART] Bot restarted successfully ✓");
} catch (error) {
console.error(
"[AUTO-RESTART] Failed to restart bot:",
error instanceof Error ? error.message : String(error),
);
}
} else {
console.log(
`[AUTO-RESTART] Bot is healthy (${client.guilds.cache.size} guilds)`,
);
}
}
// Start auto-restart cron
// Use setImmediate to ensure this runs after HTTP server is ready
setImmediate(() => {
autoRestartInterval = setInterval(autoRestartCheck, AUTO_RESTART_INTERVAL_MS);
console.log(`[CRON] Auto-restart check scheduled every 1 hour`);
// Run initial check after 30 seconds (give time for normal startup and HTTP server)
setTimeout(autoRestartCheck, 30000);
});