Skip to content

Conversation

@dangerousbeans
Copy link

@dangerousbeans dangerousbeans commented Nov 3, 2025

This update enhances the Discord bot's reliability and fixes several issues:

Core Improvements:

  • Update to Claude Sonnet 4.5 (claude-sonnet-4-5-20250929)
  • Add --permission-mode acceptEdits for autonomous operation
  • Fix exit code 143 false error reporting (SIGTERM is normal shutdown)
  • Add hook disabling mechanism for Discord bot sessions

Bug Fixes:

  • Fix MCP bridge port mismatch (now uses MCP_SERVER_PORT env variable)
  • Truncate long error messages to fit Discord's 4096 character limit
  • Prevent sound notifications during Discord bot operations

Configuration:

  • Add MCP_SERVER_PORT to environment configuration
  • Pass port configuration through to MCP bridge
  • Add CLAUDE_DISABLE_HOOKS environment variable

Documentation:

  • Add troubleshooting section for Claude Code hooks
  • Document MCP port configuration
  • Add hook disabling instructions

Testing:

  • Add tests for exit code handling (0, 143, and error codes)
  • Improve test coverage for process lifecycle

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Documentation

    • Added troubleshooting guide for Claude Code Hooks interference with the Discord bot.
  • Improvements

    • Discord messages now auto-truncate to fit embed size limits.
    • Enhanced bot reliability with improved process exit handling.
    • Configurable MCP server port (default: 3001).
    • Updated Claude model with automatic editing capabilities.

This update enhances the Discord bot's reliability and fixes several issues:

**Core Improvements:**
- Update to Claude Sonnet 4.5 (claude-sonnet-4-5-20250929)
- Add --permission-mode acceptEdits for autonomous operation
- Fix exit code 143 false error reporting (SIGTERM is normal shutdown)
- Add hook disabling mechanism for Discord bot sessions

**Bug Fixes:**
- Fix MCP bridge port mismatch (now uses MCP_SERVER_PORT env variable)
- Truncate long error messages to fit Discord's 4096 character limit
- Prevent sound notifications during Discord bot operations

**Configuration:**
- Add MCP_SERVER_PORT to environment configuration
- Pass port configuration through to MCP bridge
- Add CLAUDE_DISABLE_HOOKS environment variable

**Documentation:**
- Add troubleshooting section for Claude Code hooks
- Document MCP port configuration
- Add hook disabling instructions

**Testing:**
- Add tests for exit code handling (0, 143, and error codes)
- Improve test coverage for process lifecycle

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai
Copy link

coderabbitai bot commented Nov 3, 2025

Walkthrough

This PR introduces configurable MCP server port via environment variable, sets CLAUDE_DISABLE_HOOKS=1 to manage Claude Code Hooks behavior for Discord bot usage, refines process exit code handling to treat exit codes 0 and 143 as normal shutdowns, and adds text truncation for Discord embed descriptions to prevent length violations.

Changes

Cohort / File(s) Summary
Configuration & Environment
.env.example, .gitignore
Adds MCP_SERVER_PORT=3001 environment variable to .env.example; adds log.txt to .gitignore under logs section.
Documentation
README.md
Adds Troubleshooting subsection explaining Claude Code Hooks interference with Discord bot and provides shell snippet to check CLAUDE_DISABLE_HOOKS=1 environment flag.
MCP Server Port Configuration
mcp-bridge.cjs, src/utils/shell.ts
Replaces hard-coded port with configurable MCP_SERVER_PORT environment variable (default '3001'); updates MCP server URL and request options to use parsed port; adds MCP_SERVER_PORT to Claude command MCP config in shell utils.
Claude Manager Enhancements
src/claude/manager.ts
Adds truncateForEmbed() helper for Discord embed description limits; sets CLAUDE_DISABLE_HOOKS=1 in Claude process environment; refines exit code handling to suppress errors for codes 0, null, and 143 (SIGTERM); applies text truncation to stderr warnings and error messages.
Test Updates
test/claude/manager.test.ts
Adds mock implementations for shell utilities; renames test expectations from "responses" to "tool calls"; introduces new "process exit code handling" test suite with three tests for exit codes 0, 143, and other non-zero codes.

Sequence Diagram

sequenceDiagram
    participant Bot as Discord Bot
    participant Manager as ClaudeManager
    participant Child as Child Process
    participant Discord as Discord Channel

    Bot->>Manager: Trigger Claude action
    Manager->>Child: Spawn with CLAUDE_DISABLE_HOOKS=1
    activate Child
    Child->>Child: Code execution (hooks disabled)
    Child-->>Manager: Result/stderr message
    deactivate Child
    
    alt Exit Code: 0 or 143
        Manager->>Manager: Suppress error notification
    else Exit Code: Non-zero
        Manager->>Manager: truncateForEmbed(error)
        Manager->>Discord: Post error embed
    end
    
    Manager->>Discord: Post result (truncated if needed)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • manager.ts exit code handling: Verify that exit codes 0, null, and 143 are correctly identified as non-errors and that other exit codes properly trigger error messaging.
  • Text truncation logic: Ensure truncateForEmbed() correctly limits messages to 4096 characters and appends truncation notice appropriately across all error and warning paths.
  • Environment variable propagation: Confirm CLAUDE_DISABLE_HOOKS=1 and MCP_SERVER_PORT are consistently set and passed through all process creation and configuration points.
  • Test coverage: Review new exit code handling tests to ensure they properly mock child process lifecycle and close events with specific exit codes.

Poem

🐰 A port now flows through config streams,
Hooks disabled in Discord's dreams,
Clean shutdowns caught with gentle care,
Messages trimmed with rabbit flair—
The bot hops on with grace! 🎉

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "Improve Discord bot reliability and Claude Code integration" accurately reflects the core objectives and changes throughout the pull request. The PR encompasses multiple reliability improvements such as treating SIGTERM as a normal shutdown rather than an error, truncating long error messages to respect Discord's 4096-character embed limit, and preventing sound notifications during bot operations. It also includes Claude Code integration enhancements like disabling hooks for Discord bot sessions, upgrading to Claude Sonnet 4.5, and adding autonomous operation with --permission-mode acceptEdits. The title is specific and clear enough to convey the primary purpose without being vague or generic.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/claude/manager.ts (1)

9-17: Consider adding validation for small maxLength values.

The truncation logic is sound for the Discord embed use case (4096 chars). However, if maxLength is less than 50, the substring operation would use a negative index, which would work but might produce unexpected results.

Consider adding a guard:

 function truncateForEmbed(text: string, maxLength: number = 4096): string {
   if (text.length <= maxLength) {
     return text;
   }
+  const truncationNotice = '\n...\n[Message truncated]';
+  const availableLength = Math.max(0, maxLength - truncationNotice.length);
-  return text.substring(0, maxLength - 50) + '\n...\n[Message truncated]';
+  return text.substring(0, availableLength) + truncationNotice;
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d156fea and 7b2a06e.

📒 Files selected for processing (7)
  • .env.example (1 hunks)
  • .gitignore (1 hunks)
  • README.md (1 hunks)
  • mcp-bridge.cjs (2 hunks)
  • src/claude/manager.ts (5 hunks)
  • src/utils/shell.ts (3 hunks)
  • test/claude/manager.test.ts (3 hunks)
🧰 Additional context used
🪛 dotenv-linter (4.0.0)
.env.example

[warning] 14-14: [EndingBlankLine] No blank line at the end of the file

(EndingBlankLine)

🔇 Additional comments (13)
.gitignore (1)

17-17: LGTM!

The addition of log.txt to the ignore patterns aligns with the logging behavior introduced in src/claude/manager.ts (lines 164-168), where Claude output is appended to this file.

.env.example (1)

12-14: LGTM!

The MCP_SERVER_PORT configuration is well-documented and aligns with the implementation in mcp-bridge.cjs (line 10) and src/utils/shell.ts (line 75), where the port is consumed with the same default value.

README.md (1)

168-190: LGTM!

The troubleshooting documentation clearly explains the hook-disabling mechanism and provides a practical shell script example. This aligns perfectly with the CLAUDE_DISABLE_HOOKS=1 environment variable set in src/claude/manager.ts (line 116).

mcp-bridge.cjs (2)

10-11: LGTM!

The configurable MCP server port is properly externalized from the environment with a sensible default. This aligns with the configuration in .env.example (line 14) and usage in src/utils/shell.ts (line 75).


52-52: LGTM!

The port is correctly parsed to an integer for the HTTP request options, matching the port used in the URL at line 11.

src/utils/shell.ts (2)

35-37: LGTM!

The model upgrade to claude-sonnet-4-5-20250929 (Sonnet 4.5) provides explicit versioning for reproducibility. The --permission-mode acceptEdits addition enables autonomous editing without prompts, which is essential for the Discord bot's unattended operation.


75-75: LGTM!

The MCP_SERVER_PORT environment variable is properly passed to the MCP bridge configuration, with a consistent default of "3001" matching mcp-bridge.cjs (line 10) and .env.example (line 14).

test/claude/manager.test.ts (2)

18-23: LGTM!

The shell utility mocks provide appropriate test isolation for ClaudeManager tests, with simple implementations sufficient for validating the manager's behavior without invoking actual shell command construction.


209-327: LGTM!

The exit code handling test suite comprehensively validates the refined error reporting behavior introduced in src/claude/manager.ts (lines 211-224):

  • Exit code 0 (success) suppresses error messaging
  • Exit code 143 (SIGTERM) treats termination as normal shutdown
  • Actual failure codes trigger error embeds with the exit code

The test setup correctly simulates the process lifecycle and verifies Discord messaging behavior.

src/claude/manager.ts (4)

116-116: LGTM!

Setting CLAUDE_DISABLE_HOOKS=1 prevents hook execution during Discord bot operations, which is well-documented in the README troubleshooting section (lines 172-189). This avoids unwanted side effects like audio notifications during automated bot interactions.


211-224: LGTM!

The refined exit code handling correctly distinguishes between normal shutdowns and actual failures:

  • Exit code 0: success
  • Exit code null: process terminated without code
  • Exit code 143: SIGTERM signal (128 + 15), indicating graceful termination

Only non-zero, non-null, non-143 codes trigger error embeds. This prevents false error reporting during normal bot shutdown operations and is well-covered by the test suite in test/claude/manager.test.ts (lines 209-327).


241-241: LGTM!

The stderr output is appropriately truncated to respect Discord's 4096-character embed description limit, preventing message delivery failures for long error outputs.


261-261: LGTM!

Process error messages are consistently truncated using the same helper, ensuring all error embeds respect Discord's character limits.


# MCP Server Port (optional, defaults to 3001)
# Change this if port 3001 is already in use
MCP_SERVER_PORT=3001
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Add blank line at end of file.

The dotenv-linter correctly flags a missing blank line at the end of the file, which is a common convention for text files.

Apply this diff:

 MCP_SERVER_PORT=3001
+
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
MCP_SERVER_PORT=3001
MCP_SERVER_PORT=3001
🧰 Tools
🪛 dotenv-linter (4.0.0)

[warning] 14-14: [EndingBlankLine] No blank line at the end of the file

(EndingBlankLine)

🤖 Prompt for AI Agents
In .env.example around line 14, the file is missing a trailing blank line; add a
single newline character at the end of the file so the file terminates with a
blank line (save the file with an ending newline).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant