Skip to main content
Glama
README.md
<div align="center">
  <h1>๐Ÿค– Discord MCP Server</h1>
  <p><strong>A comprehensive Model Context Protocol server for Discord integration</strong></p>
  
  <p>
    <a href="https://github.com/lokeshpanthangi/Discord-MCP/stargazers"><img src="https://img.shields.io/github/stars/lokeshpanthangi/Discord-MCP?style=for-the-badge" alt="Stars"></a>
    <a href="https://github.com/lokeshpanthangi/Discord-MCP/network/members"><img src="https://img.shields.io/github/forks/lokeshpanthangi/Discord-MCP?style=for-the-badge" alt="Forks"></a>
    <a href="https://github.com/lokeshpanthangi/Discord-MCP/issues"><img src="https://img.shields.io/github/issues/lokeshpanthangi/Discord-MCP?style=for-the-badge" alt="Issues"></a>
    <a href="https://github.com/lokeshpanthangi/Discord-MCP/blob/main/LICENSE"><img src="https://img.shields.io/github/license/lokeshpanthangi/Discord-MCP?style=for-the-badge" alt="License"></a>
  </p>
  
  <p>
    <a href="#-features">Features</a> โ€ข
    <a href="#-quick-start">Quick Start</a> โ€ข
    <a href="#-installation">Installation</a> โ€ข
    <a href="#-configuration">Configuration</a> โ€ข
    <a href="#-api-reference">API Reference</a> โ€ข
    <a href="#-contributing">Contributing</a>
  </p>
</div>

---

## ๐Ÿ“‹ Table of Contents

- [โœจ Features](#-features)
- [๐Ÿš€ Quick Start](#-quick-start)
- [๐Ÿ“ฆ Installation](#-installation)
- [โš™๏ธ Configuration](#๏ธ-configuration)
- [๐Ÿ”ง Setup Guide](#-setup-guide)
- [๐Ÿ› ๏ธ Available Tools](#๏ธ-available-tools)
- [๐Ÿ” Authentication](#-authentication)
- [๐Ÿ“Š Monitoring](#-monitoring)
- [๐Ÿงช Testing](#-testing)
- [๐Ÿ“š API Reference](#-api-reference)
- [๐Ÿ›ก๏ธ Security](#๏ธ-security)
- [๐Ÿค Contributing](#-contributing)
- [๐Ÿ“„ License](#-license)

## โœจ Features

### ๐ŸŽฏ Core Capabilities
- **๐Ÿ”— Discord Integration**: Full Discord API support with 5 powerful tools
- **๐Ÿ” Enterprise Security**: Multi-tenant authentication with API key management
- **โšก Rate Limiting**: Configurable rate limits (30/min, 500/hour, 5000/day)
- **๐Ÿ“Š Real-time Monitoring**: Built-in MCP Inspector dashboard
- **๐Ÿ” Comprehensive Logging**: Audit trails and security event tracking
- **๐Ÿงช Testing Ready**: Jest framework with 80%+ coverage threshold

### ๐Ÿ› ๏ธ Discord Tools
| Tool | Description | Use Case |
|------|-------------|----------|
| `get_channel_info` | Retrieve detailed channel information | Channel analytics, moderation |
| `get_messages` | Fetch messages with filtering options | Content analysis, history |
| `search_messages` | Advanced message search capabilities | Content discovery, compliance |
| `send_message` | Send messages by channel ID or name | Automated notifications, responses |
| `moderate_content` | Delete messages and moderate content | Community management, safety |

### ๐Ÿ—๏ธ Architecture Highlights
- **๐Ÿ”„ MCP Protocol**: Full Model Context Protocol compliance
- **๐Ÿข Multi-tenancy**: Isolated client management per API key
- **๐Ÿ›ก๏ธ Security First**: Token hashing, no persistent storage
- **๐Ÿ“ˆ Scalable**: Automatic client cleanup and resource management

```bash
# Clone the repository
git clone https://github.com/lokeshpanthangi/Discord-MCP.git
cd Discord-MCP

# Install dependencies
npm install

# Configure environment
cp .env.example .env
# Edit .env with your credentials

# Start the server
npm start

# Open MCP Inspector (optional)
# Visit http://localhost:3001
```

## ๐Ÿ“ฆ Installation

### Prerequisites

- **Node.js** >= 18.0.0
- **npm** >= 8.0.0
- **Discord Bot Token** ([Create one here](https://discord.com/developers/applications))
- **Discord Server** with bot permissions

### Step-by-Step Installation

1. **Clone the Repository**
   ```bash
   git clone https://github.com/lokeshpanthangi/Discord-MCP.git
   cd Discord-MCP
   ```

2. **Install Dependencies**
   ```bash
   npm install
   ```

3. **Environment Setup**
   ```bash
   cp .env.example .env
   ```

4. **Configure Environment Variables** (see [Configuration](#๏ธ-configuration))

5. **Start the Server**
   ```bash
   npm start
   ```

## โš™๏ธ Configuration

### Environment Variables

Create a `.env` file in the root directory:

```env
# Required: Discord Bot Configuration
DISCORD_BOT_TOKEN=your_discord_bot_token_here

# Required: MCP Server Authentication
MCP_API_KEY=your_secure_api_key_here

# Optional: Server Configuration
MCP_SERVER_NAME=discord-mcp-server
NODE_ENV=production

# Optional: Monitoring
MCP_INSPECTOR_PORT=3001

# Optional: Logging
LOG_LEVEL=info
```

### Discord Bot Setup

1. **Create Discord Application**
   - Visit [Discord Developer Portal](https://discord.com/developers/applications)
   - Click "New Application" and give it a name
   - Navigate to "Bot" section
   - Click "Add Bot"

2. **Configure Bot Permissions**
   ```
   โœ… Send Messages
   โœ… Read Message History
   โœ… View Channels
   โœ… Manage Messages (for moderation)
   โœ… Read Messages/View Channels
   ```

3. **Get Bot Token**
   - In Bot section, click "Copy" under Token
   - Add to your `.env` file as `DISCORD_BOT_TOKEN`

4. **Invite Bot to Server**
   ```
   https://discord.com/api/oauth2/authorize?client_id=YOUR_CLIENT_ID&permissions=8192&scope=bot
   ```

## ๐Ÿ”ง Setup Guide

### For Claude Desktop Integration

1. **Configure Claude Desktop**
   
   Add to your `claude_desktop_config.json`:
   ```json
   {
     "mcpServers": {
       "discord-mcp": {
         "command": "node",
         "args": ["server.js"],
         "cwd": "/path/to/Discord-MCP",
         "env": {
           "MCP_INSPECTOR_PORT": "3001"
         }
       }
     }
   }
   ```

2. **Restart Claude Desktop**

3. **Verify Connection**
   - Open Claude Desktop
   - Look for Discord tools in the interface
   - Test with a simple command

### For Development

1. **Install Development Dependencies**
   ```bash
   npm install
   ```

2. **Run in Development Mode**
   ```bash
   npm run dev
   ```

3. **Run Tests**
   ```bash
   npm test
   npm run test:coverage
   ```

4. **Code Quality**
   ```bash
   npm run lint
   npm run format
   npm run validate
   ```

### 1. ๐Ÿ“‹ get_channel_info

**Purpose**: Retrieve comprehensive information about Discord channels

```javascript
// Usage Example
{
  "channelId": "1234567890123456789"
}

// Response
{
  "id": "1234567890123456789",
  "name": "general",
  "type": "Text",
  "topic": "Welcome to our server!",
  "memberCount": 150,
  "createdAt": "2023-01-01T00:00:00.000Z"
}
```

### 2. ๐Ÿ“จ get_messages

**Purpose**: Fetch messages from channels with filtering options

```javascript
// Usage Example
{
  "channelId": "1234567890123456789",
  "limit": 10,
  "before": "1234567890123456789"
}

// Response
{
  "messages": [
    {
      "id": "1234567890123456789",
      "content": "Hello world!",
      "author": "username#1234",
      "timestamp": "2023-01-01T00:00:00.000Z"
    }
  ]
}
```

### 3. ๐Ÿ” search_messages

**Purpose**: Advanced message search with multiple filters

```javascript
// Usage Example
{
  "channelId": "1234567890123456789",
  "query": "important announcement",
  "authorId": "9876543210987654321",
  "limit": 5
}
```

### 4. ๐Ÿ“ค send_message

**Purpose**: Send messages to channels (supports both ID and name)

```javascript
// By Channel ID
{
  "channelId": "1234567890123456789",
  "content": "Hello from MCP!"
}

// By Channel Name
{
  "channelName": "general",
  "content": "Hello from MCP!"
}
```

### 5. ๐Ÿ›ก๏ธ moderate_content

**Purpose**: Delete messages and moderate content

```javascript
// Usage Example
{
  "channelId": "1234567890123456789",
  "messageId": "1234567890123456789",
  "reason": "Inappropriate content"
}
```

## ๐Ÿ” Authentication

### API Key Management

- **Environment-based**: Store API keys in `.env` file
- **Multi-tenant**: Each API key gets isolated Discord client
- **Secure**: Keys are hashed for client identification
- **No Persistence**: Tokens never stored permanently

### Security Features

- โœ… **Token Hashing**: Bot tokens hashed for security
- โœ… **Client Isolation**: Separate Discord clients per tenant
- โœ… **Automatic Cleanup**: Unused clients cleaned up
- โœ… **Audit Logging**: All authentication attempts logged
- โœ… **Rate Limiting**: Configurable request limits

## ๐Ÿ“Š Monitoring

### MCP Inspector Dashboard

Access real-time monitoring at `http://localhost:3001`

**Features:**
- ๐Ÿ“Š **Real-time Metrics**: Request counts, response times
- ๐Ÿ” **Request Logging**: Detailed request/response inspection
- ๐Ÿ“ˆ **Performance Monitoring**: Tool execution statistics
- ๐Ÿšจ **Error Tracking**: Failed requests and error analysis
- ๐Ÿ‘ฅ **Multi-tenant View**: Per-client usage statistics

### Logging System

```
logs/
โ”œโ”€โ”€ audit.log      # Authentication and authorization events
โ”œโ”€โ”€ error.log      # Application errors and exceptions
โ””โ”€โ”€ security.log   # Security-related events and violations
```

## ๐Ÿงช Testing

### Test Coverage

- **Target**: 80%+ code coverage
- **Framework**: Jest with comprehensive test suites
- **Types**: Unit tests, integration tests, security tests

### Running Tests

```bash
# Run all tests
npm test

# Watch mode for development
npm run test:watch

# Generate coverage report
npm run test:coverage

# Integration tests
npm run test:integration

# Multi-tenancy tests
npm run test:multi
```

### Test Structure

```
__tests__/
โ”œโ”€โ”€ tools/
โ”‚   โ”œโ”€โ”€ get_channel_info.test.js
โ”‚   โ”œโ”€โ”€ get_messages.test.js
โ”‚   โ”œโ”€โ”€ search_messages.test.js
โ”‚   โ”œโ”€โ”€ send_message.test.js
โ”‚   โ””โ”€โ”€ moderate_content.test.js
โ”œโ”€โ”€ middleware/
โ”‚   โ””โ”€โ”€ auth.test.js
โ””โ”€โ”€ utils/
    โ”œโ”€โ”€ rate-limiter.test.js
    โ””โ”€โ”€ audit-logger.test.js
```

## ๐Ÿ“š API Reference

### Server Configuration

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `MCP_SERVER_NAME` | string | `discord-mcp-server` | Server identifier |
| `NODE_ENV` | string | `development` | Environment mode |
| `MCP_INSPECTOR_PORT` | number | `3001` | Inspector dashboard port |
| `LOG_LEVEL` | string | `info` | Logging verbosity |

### Rate Limiting

| Limit Type | Default | Configurable |
|------------|---------|-------------|
| Requests per minute | 30 | โœ… |
| Requests per hour | 500 | โœ… |
| Requests per day | 5000 | โœ… |

### Error Codes

| Code | Description | Resolution |
|------|-------------|------------|
| `AUTH_001` | Invalid API key | Check MCP_API_KEY in .env |
| `AUTH_002` | Missing API key | Add MCP_API_KEY to request |
| `RATE_001` | Rate limit exceeded | Wait for rate limit reset |
| `DISCORD_001` | Invalid bot token | Verify DISCORD_BOT_TOKEN |
| `DISCORD_002` | Missing permissions | Check bot permissions |

## ๐Ÿ›ก๏ธ Security

### Best Practices

- ๐Ÿ” **Environment Variables**: Never commit secrets to repository
- ๐Ÿ”‘ **API Key Rotation**: Regularly rotate API keys
- ๐Ÿ“ **Audit Logging**: Monitor all authentication attempts
- ๐Ÿšซ **Rate Limiting**: Prevent abuse with configurable limits
- ๐Ÿ”’ **Token Security**: Bot tokens are hashed, never stored

### Security Headers

```javascript
// Implemented security measures
- API Key validation
- Request rate limiting
- Audit trail logging
- Client isolation
- Automatic cleanup
```

## ๐Ÿค Contributing

We welcome contributions! Please follow these steps:

1. **Fork the Repository**
   ```bash
   git fork https://github.com/lokeshpanthangi/Discord-MCP.git
   ```

2. **Create Feature Branch**
   ```bash
   git checkout -b feature/amazing-feature
   ```

3. **Make Changes**
   - Follow existing code style
   - Add tests for new features
   - Update documentation

4. **Run Quality Checks**
   ```bash
   npm run validate
   ```

5. **Commit Changes**
   ```bash
   git commit -m "feat: add amazing feature"
   ```

6. **Push and Create PR**
   ```bash
   git push origin feature/amazing-feature
   ```

### Development Guidelines

- โœ… **Code Style**: Use Prettier and ESLint
- โœ… **Testing**: Maintain 80%+ coverage
- โœ… **Documentation**: Update README for new features
- โœ… **Security**: Follow security best practices
- โœ… **Performance**: Consider rate limiting and resource usage

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

<div align="center">
  <p><strong>Made with โค๏ธ by <a href="https://github.com/lokeshpanthangi">Lokesh Panthangi</a></strong></p>
  <p>
    <a href="https://github.com/lokeshpanthangi/Discord-MCP/issues">Report Bug</a> โ€ข
    <a href="https://github.com/lokeshpanthangi/Discord-MCP/issues">Request Feature</a> โ€ข
    <a href="https://github.com/lokeshpanthangi/Discord-MCP/discussions">Discussions</a>
  </p>
</div>

- **Send Messages**: Send messages to Discord channels
- **Get Messages**: Retrieve recent messages from channels  
- **Get Channel Info**: Fetch channel details and metadata
- **Search Messages**: Search for messages within channels
- **Moderate Content**: Perform moderation actions (delete messages, kick/ban users)
- **Multi-Tenant Support**: Support multiple Discord bots with isolated clients
- **Claude Desktop Integration**: Ready-to-use with Claude Desktop application
- **Environment Variable Support**: Flexible token configuration

## ๐Ÿš€ Quick Start

### Prerequisites

- Node.js 16+ installed
- Discord bot token ([Create one here](https://discord.com/developers/applications))
- Claude Desktop (for desktop integration)

### Installation

1. **Clone the repository**
   ```bash
   git clone <repository-url>
   cd Discord-MCP
   ```

2. **Install dependencies**
   ```bash
   npm install
   ```

3. **Set up environment variables**
   ```bash
   # Create .env file
   echo "DISCORD_BOT_TOKEN=your_bot_token_here" > .env
   ```

4. **Test the server**
   ```bash
   node test-claude-desktop.js
   ```

## ๐Ÿ–ฅ๏ธ Claude Desktop Integration

### Step 1: Configure Claude Desktop

Create or edit your Claude Desktop configuration file:

**Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
**macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
**Linux**: `~/.config/claude-desktop/claude_desktop_config.json`

### Step 2: Add MCP Server Configuration

```json
{
  "mcpServers": {
    "discord": {
      "command": "node",
      "args": ["path/to/your/Discord-MCP/server.js"],
      "env": {
        "DISCORD_BOT_TOKEN": "your_discord_bot_token_here",
        "NODE_ENV": "production"
      }
    }
  }
}
```

### Step 3: Restart Claude Desktop

Restart Claude Desktop to load the new MCP server configuration.

### Step 4: Start Using Discord Commands

```
User: "Send a message 'Hello World!' to Discord channel 1234567890123456789"
Claude: I'll send that message to Discord for you!
```

## ๐Ÿ› ๏ธ Available Tools

### 1. Send Message
```javascript
{
  "name": "send_message",
  "arguments": {
    "channelId": "1234567890123456789",
    "content": "Hello from Claude!"
  }
}
```

### 2. Get Messages
```javascript
{
  "name": "get_messages",
  "arguments": {
    "channelId": "1234567890123456789",
    "limit": 10
  }
}
```

### 3. Get Channel Info
```javascript
{
  "name": "get_channel_info",
  "arguments": {
    "channelId": "1234567890123456789"
  }
}
```

### 4. Search Messages
```javascript
{
  "name": "search_messages",
  "arguments": {
    "channelId": "1234567890123456789",
    "query": "important announcement",
    "limit": 50
  }
}
```

### 5. Moderate Content
```javascript
{
  "name": "moderate_content",
  "arguments": {
    "action": "delete_message",
    "channelId": "1234567890123456789",
    "messageId": "9876543210987654321",
    "guildId": "1111111111111111111",
    "reason": "Spam content"
  }
}
```

## ๐Ÿ” Multi-Tenancy Support

The server supports multiple Discord bots simultaneously:

### Option 1: Environment Variable (Recommended for Claude Desktop)
```bash
DISCORD_BOT_TOKEN=your_default_token
```

### Option 2: Per-Request Token
```javascript
{
  "name": "send_message",
  "arguments": {
    "discordBotToken": "specific_bot_token",
    "channelId": "1234567890123456789",
    "content": "Hello!"
  }
}
```

## ๐Ÿ“ Project Structure

```
Discord-MCP/
โ”œโ”€โ”€ server.js                     # Main MCP server
โ”œโ”€โ”€ tools/
โ”‚   โ”œโ”€โ”€ send_message.js           # Send messages tool
โ”‚   โ”œโ”€โ”€ get_messages.js           # Get messages tool
โ”‚   โ”œโ”€โ”€ get_channel_info.js       # Channel info tool
โ”‚   โ”œโ”€โ”€ search_messages.js        # Search messages tool
โ”‚   โ””โ”€โ”€ moderate_content.js       # Moderation tool
โ”œโ”€โ”€ test-multi-tenant.js          # Multi-tenancy test
โ”œโ”€โ”€ test-claude-desktop.js        # Claude Desktop test
โ”œโ”€โ”€ CLAUDE_DESKTOP_SETUP.md       # Detailed setup guide
โ”œโ”€โ”€ MULTI_TENANT_SETUP.md         # Multi-tenancy guide
โ”œโ”€โ”€ claude_desktop_config.example.json # Example config
โ””โ”€โ”€ package.json
```

## ๐Ÿงช Testing

### Test Multi-Tenancy
```bash
node test-multi-tenant.js
```

### Test Claude Desktop Integration
```bash
node test-claude-desktop.js
```

## ๐Ÿ”ง Configuration Options

### Environment Variables

- `DISCORD_BOT_TOKEN`: Default Discord bot token
- `NODE_ENV`: Environment mode (`development` or `production`)
- `LOG_LEVEL`: Logging level (`debug`, `info`, `warn`, `error`)

### Bot Permissions Required

Your Discord bot needs these permissions:
- `Send Messages`
- `Read Message History`
- `View Channels`
- `Manage Messages` (for moderation)
- `Kick Members` (for moderation)
- `Ban Members` (for moderation)

## ๐Ÿ›ก๏ธ Security Features

- **Token Hashing**: Bot tokens are hashed for client identification
- **No Token Persistence**: Tokens are never stored permanently
- **Client Isolation**: Each bot token gets its own Discord client
- **Automatic Cleanup**: Unused clients are cleaned up automatically
- **Input Validation**: All inputs are validated before processing

## ๐Ÿ“š Documentation

- [Claude Desktop Setup Guide](./CLAUDE_DESKTOP_SETUP.md)
- [Multi-Tenant Setup Guide](./MULTI_TENANT_SETUP.md)

## ๐Ÿค Usage Examples

### Natural Language Commands with Claude

```
โœ… "Send 'Meeting in 5 minutes' to the general channel"
โœ… "Get the last 10 messages from announcements"
โœ… "Search for 'project update' in dev-team channel"
โœ… "Get information about channel ID 1234567890"
โœ… "Delete spam message ID 9876543210"
```

### Programmatic Usage

```javascript
const { MCPServer } = require('./server');

const server = new MCPServer();
server.start();
```

## ๐Ÿšจ Troubleshooting

### Common Issues

1. **"Invalid token" error**
   - Verify your Discord bot token is correct
   - Check bot permissions in Discord server
   - Ensure bot is added to target servers

2. **"Channel not found" error**
   - Verify channel ID is correct
   - Check bot has access to the channel
   - Ensure channel exists and bot is in the server

3. **"Permission denied" error**
   - Check bot permissions in Discord
   - Verify bot role hierarchy
   - Ensure required intents are enabled

### Debug Mode

Enable debug logging:
```bash
LOG_LEVEL=debug node server.js
```

## ๐Ÿ“„ License

MIT License - see LICENSE file for details.

## ๐Ÿค– About MCP

This server implements the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/), allowing AI assistants to interact with Discord through a standardized interface.

---

**Ready to integrate Discord with Claude? Follow the [Claude Desktop Setup Guide](./CLAUDE_DESKTOP_SETUP.md) to get started!** ๐Ÿš€