Compare commits

..

1 Commits

Author SHA1 Message Date
Kenneth Lien
aa71c24314 discord: port resilience fixes from telegram
Same patterns as #812/#813 for the discord channel:
- process-level unhandledRejection/uncaughtException handlers
- client.on('error') to log discord.js errors
- mcp.notification().catch() so inbound delivery failures surface
- stdin close / SIGTERM -> client.destroy() + exit (zombie fix)
- .unref() the approval-check interval
- client.login().catch() to log+exit on bad token instead of crashing

Discord is inherently more resilient than telegram (discord.js
auto-reconnects, no 409 equivalent), but these gaps were still there.
2026-03-20 11:28:51 -07:00
6 changed files with 54 additions and 49 deletions

View File

@@ -1,20 +1,11 @@
{
"name": "discord",
"description": "Discord channel for Claude Code messaging bridge with built-in access control. Manage pairing, allowlists, and policy via /discord:access.",
"version": "0.0.2",
"description": "Discord channel for Claude Code \u2014 messaging bridge with built-in access control. Manage pairing, allowlists, and policy via /discord:access.",
"version": "0.0.1",
"keywords": [
"discord",
"messaging",
"channel",
"mcp"
],
"userConfig": {
"DISCORD_BOT_TOKEN": {
"type": "string",
"title": "Bot Token",
"description": "Bot token from the Discord Developer Portal. Stored in keychain (macOS) or ~/.claude/.credentials.json with 0600 permissions elsewhere. Never written to settings.json.",
"required": true,
"sensitive": true
}
}
]
}

View File

@@ -2,10 +2,7 @@
"mcpServers": {
"discord": {
"command": "bun",
"args": ["run", "--cwd", "${CLAUDE_PLUGIN_ROOT}", "--shell=bun", "--silent", "start"],
"env": {
"DISCORD_BOT_TOKEN": "${user_config.DISCORD_BOT_TOKEN}"
}
"args": ["run", "--cwd", "${CLAUDE_PLUGIN_ROOT}", "--shell=bun", "--silent", "start"]
}
}
}

View File

@@ -34,12 +34,10 @@ const ACCESS_FILE = join(STATE_DIR, 'access.json')
const APPROVED_DIR = join(STATE_DIR, 'approved')
const ENV_FILE = join(STATE_DIR, '.env')
// Token is injected via ${user_config.DISCORD_BOT_TOKEN} from .mcp.json —
// prompted at enable time, stored in keychain (macOS) or .credentials.json 0600
// elsewhere. The .env file below is a legacy fallback for users configured
// before H1 #3617646 — real env wins, so the injected value takes precedence.
// Load ~/.claude/channels/discord/.env into process.env. Real env wins.
// Plugin-spawned servers don't get an env block — this is where the token lives.
try {
// Defensive chmod for legacy .env files (no-op on Windows).
// Token is a credential — lock to owner. No-op on Windows (would need ACLs).
chmodSync(ENV_FILE, 0o600)
for (const line of readFileSync(ENV_FILE, 'utf8').split('\n')) {
const m = line.match(/^(\w+)=(.*)$/)
@@ -53,13 +51,22 @@ const STATIC = process.env.DISCORD_ACCESS_MODE === 'static'
if (!TOKEN) {
process.stderr.write(
`discord channel: DISCORD_BOT_TOKEN required\n` +
` re-enter via: /plugin manage → discord → Configure options\n` +
` (stored in keychain/credentials.json, not settings.json)\n`,
` set in ${ENV_FILE}\n` +
` format: DISCORD_BOT_TOKEN=MTIz...\n`,
)
process.exit(1)
}
const INBOX_DIR = join(STATE_DIR, 'inbox')
// Last-resort safety net — without these the process dies silently on any
// unhandled promise rejection. With them it logs and keeps serving tools.
process.on('unhandledRejection', err => {
process.stderr.write(`discord channel: unhandled rejection: ${err}\n`)
})
process.on('uncaughtException', err => {
process.stderr.write(`discord channel: uncaught exception: ${err}\n`)
})
const client = new Client({
intents: [
GatewayIntentBits.DirectMessages,
@@ -344,7 +351,7 @@ function checkApprovals(): void {
}
}
if (!STATIC) setInterval(checkApprovals, 5000)
if (!STATIC) setInterval(checkApprovals, 5000).unref()
// Discord caps messages at 2000 chars (hard limit — larger sends reject).
// Split long replies, preferring paragraph boundaries when chunkMode is
@@ -639,6 +646,25 @@ mcp.setRequestHandler(CallToolRequestSchema, async req => {
await mcp.connect(new StdioServerTransport())
// When Claude Code closes the MCP connection, stdin gets EOF. Without this
// the gateway stays connected as a zombie holding resources.
let shuttingDown = false
function shutdown(): void {
if (shuttingDown) return
shuttingDown = true
process.stderr.write('discord channel: shutting down\n')
setTimeout(() => process.exit(0), 2000)
void Promise.resolve(client.destroy()).finally(() => process.exit(0))
}
process.stdin.on('end', shutdown)
process.stdin.on('close', shutdown)
process.on('SIGTERM', shutdown)
process.on('SIGINT', shutdown)
client.on('error', err => {
process.stderr.write(`discord channel: client error: ${err}\n`)
})
client.on('messageCreate', msg => {
if (msg.author.bot) return
handleInbound(msg).catch(e => process.stderr.write(`discord: handleInbound failed: ${e}\n`))
@@ -687,7 +713,7 @@ async function handleInbound(msg: Message): Promise<void> {
// forgeable by any allowlisted sender typing that string.
const content = msg.content || (atts.length > 0 ? '(attachment)' : '')
void mcp.notification({
mcp.notification({
method: 'notifications/claude/channel',
params: {
content,
@@ -700,6 +726,8 @@ async function handleInbound(msg: Message): Promise<void> {
...(atts.length > 0 ? { attachment_count: String(atts.length), attachments: atts.join('; ') } : {}),
},
},
}).catch(err => {
process.stderr.write(`discord channel: failed to deliver inbound to Claude: ${err}\n`)
})
}
@@ -707,4 +735,7 @@ client.once('ready', c => {
process.stderr.write(`discord channel: gateway connected as ${c.user.tag}\n`)
})
await client.login(TOKEN)
client.login(TOKEN).catch(err => {
process.stderr.write(`discord channel: login failed: ${err}\n`)
process.exit(1)
})

View File

@@ -1,20 +1,11 @@
{
"name": "telegram",
"description": "Telegram channel for Claude Code messaging bridge with built-in access control. Manage pairing, allowlists, and policy via /telegram:access.",
"version": "0.0.2",
"description": "Telegram channel for Claude Code \u2014 messaging bridge with built-in access control. Manage pairing, allowlists, and policy via /telegram:access.",
"version": "0.0.1",
"keywords": [
"telegram",
"messaging",
"channel",
"mcp"
],
"userConfig": {
"TELEGRAM_BOT_TOKEN": {
"type": "string",
"title": "Bot Token",
"description": "Bot token from @BotFather — format is 123456789:AAH... Stored in keychain (macOS) or ~/.claude/.credentials.json with 0600 permissions elsewhere. Never written to settings.json.",
"required": true,
"sensitive": true
}
}
]
}

View File

@@ -2,10 +2,7 @@
"mcpServers": {
"telegram": {
"command": "bun",
"args": ["run", "--cwd", "${CLAUDE_PLUGIN_ROOT}", "--shell=bun", "--silent", "start"],
"env": {
"TELEGRAM_BOT_TOKEN": "${user_config.TELEGRAM_BOT_TOKEN}"
}
"args": ["run", "--cwd", "${CLAUDE_PLUGIN_ROOT}", "--shell=bun", "--silent", "start"]
}
}
}

View File

@@ -27,12 +27,10 @@ const ACCESS_FILE = join(STATE_DIR, 'access.json')
const APPROVED_DIR = join(STATE_DIR, 'approved')
const ENV_FILE = join(STATE_DIR, '.env')
// Token is injected via ${user_config.TELEGRAM_BOT_TOKEN} from .mcp.json —
// prompted at enable time, stored in keychain (macOS) or .credentials.json 0600
// elsewhere. The .env file below is a legacy fallback for users configured
// before H1 #3617646 — real env wins, so the injected value takes precedence.
// Load ~/.claude/channels/telegram/.env into process.env. Real env wins.
// Plugin-spawned servers don't get an env block — this is where the token lives.
try {
// Defensive chmod for legacy .env files (no-op on Windows).
// Token is a credential — lock to owner. No-op on Windows (would need ACLs).
chmodSync(ENV_FILE, 0o600)
for (const line of readFileSync(ENV_FILE, 'utf8').split('\n')) {
const m = line.match(/^(\w+)=(.*)$/)
@@ -46,8 +44,8 @@ const STATIC = process.env.TELEGRAM_ACCESS_MODE === 'static'
if (!TOKEN) {
process.stderr.write(
`telegram channel: TELEGRAM_BOT_TOKEN required\n` +
` re-enter via: /plugin manage → telegram → Configure options\n` +
` (stored in keychain/credentials.json, not settings.json)\n`,
` set in ${ENV_FILE}\n` +
` format: TELEGRAM_BOT_TOKEN=123456789:AAH...\n`,
)
process.exit(1)
}