Discord MCP Server
by suvidha-2401
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!** ๐This server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessNo issues