Skip to main content
Glama

@devli13/mcp-discord

npm License: MIT

MCP-сервер для Discord. Отправляйте сообщения, модерируйте, управляйте каналами, проверяйте серверы — из Claude Code, агентов Paperclip, Gemini CLI или любого другого MCP-совместимого клиента.

Чистая обертка REST. Без Gateway. Без базы данных. Только API Discord v10 в виде 26 хорошо задокументированных инструментов с ограничением частоты запросов (rate limiting) для каждого маршрута и структурированными результатами ошибок.


Зачем

API Discord обширен и неудобен для агентов при вызове через обычный curl. Агенты сталкиваются с ограничениями частоты запросов, неправильно обрабатывают 429 ошибки, путаются в причинах аудита, забывают курсоры пагинации. Этот MCP решает это раз и навсегда, чтобы агенты могли сосредоточиться на намерениях: «удалить то спам-сообщение», «опубликовать ежедневную сводку в #mod-log», «заблокировать @user на час».

Также отлично подходит для людей. Подключившись к Claude Code, вы можете сказать: «сделай краткую сводку последних 50 сообщений в моем Discord-канале #dev», и Claude просто сделает это.


Related MCP server: Discord Bridge MCP Server

Установка

npm install -g @devli13/mcp-discord

Или через npx (без установки):

DISCORD_BOT_TOKEN=<your-token> npx -y @devli13/mcp-discord

Настройка

1. Создайте бота Discord

  1. Перейдите на https://discord.com/developers/applications → New Application

  2. Добавьте Bot в приложение

  3. Скопируйте токен бота — это ваш DISCORD_BOT_TOKEN

  4. Пригласите бота на свой сервер, используя генератор URL OAuth2 (область действия: bot). Выберите разрешения в зависимости от того, что должен делать MCP (например, «Управление сообщениями» для удаления, «Модерация участников» для тайм-аутов)

2. Подключите его к вашему MCP-клиенту

Claude Code:

claude mcp add discord \
  --env DISCORD_BOT_TOKEN=<your-token> \
  -- npx -y @devli13/mcp-discord

Paperclip mcp-gateway (.mcp.json):

{
  "mcpServers": {
    "discord": {
      "command": "npx",
      "args": ["-y", "@devli13/mcp-discord"],
      "env": {
        "DISCORD_BOT_TOKEN": "<your-token>"
      }
    }
  }
}

Gemini CLI (~/.gemini/config.json):

{
  "mcpServers": {
    "discord": {
      "command": "npx",
      "args": ["-y", "@devli13/mcp-discord"]
    }
  }
}

3. (Опционально) Включите привилегированные интенты

Если вы хотите получать список участников сервера (discord_list_members) или использовать этот MCP вместе с сопутствующим плагином для входящих событий, включите Server Members Intent и Message Content Intent в настройках вашего бота на портале разработчика. Они не требуются для большинства операций MCP — только для определенных конечных точек.


Справочник инструментов

Все инструменты имеют префикс discord_* и возвращают либо JSON-блок (в случае успеха), либо отформатированное сообщение об ошибке (в случае неудачи). Ни один из них не вызывает исключений — каждый инструмент возвращает пригодный для использования строковый результат.

Сообщения (8)

Инструмент

Назначение

discord_send_message

Отправка в канал. Поддерживает эмбеды, ответы, управление упоминаниями

discord_edit_message

Редактирование собственного сообщения бота

discord_delete_message

Удаление одного сообщения (ботом или другими, при наличии прав «Управление сообщениями»)

discord_bulk_delete_messages

Удаление 2-100 сообщений (младше 14 дней) за один вызов

discord_get_message

Получение одного сообщения по ID

discord_list_messages

История канала с пагинацией (курсоры before/after/around)

discord_pin_message / discord_unpin_message

Управление закрепленными сообщениями

Реакции (3)

Инструмент

Назначение

discord_add_reaction

Бот добавляет реакцию

discord_remove_reaction

Удаление реакции бота или пользователя

discord_get_reactions

Список пользователей, отреагировавших эмодзи

Каналы и ветки (5)

Инструмент

Назначение

discord_list_channels

Все каналы на сервере

discord_get_channel

Детали одного канала

discord_create_thread

Создание новой ветки (публичной или приватной, привязанной или отдельной)

discord_list_active_threads

Все активные ветки на сервере

discord_send_typing

Запуск индикатора «бот печатает…»

Модерация (6)

Инструмент

Назначение

discord_get_member

Профиль участника (роли, дата вступления, состояние тайм-аута)

discord_list_members

Список участников с пагинацией (требуется интент Server Members)

discord_timeout_user

Заглушение через communication_disabled_until (макс. 28 дней, 0 для снятия)

discord_kick_user

Удаление с сервера

discord_add_role / discord_remove_role

Управление ролями

Информация о сервере (4)

Инструмент

Назначение

discord_list_guilds

Все серверы, на которых есть бот

discord_get_guild

Детали одного сервера

discord_list_roles

Все роли, отсортированные по позиции

discord_get_audit_log

Недавние записи журнала аудита (фильтрация по пользователю, действию и т.д.)

Не включено (намеренно):

  • ban/unban — намеренно. Используйте интерфейс Discord; необратимые действия не должны выполняться одним вызовом агента

  • Создание/удаление/редактирование каналов — высокий риск, используйте интерфейс

  • CRUD вебхуков — не требуется для большинства сценариев агентов; можно добавить в будущем релизе

  • Голосовые операции, управление стикерами/эмодзи — вне области действия v0.1


Пример: краткая сводка канала через Claude Code

User: Summarize the last 30 messages in the #dev channel of my Discord server, guild ID 1234...

Claude (calls discord_list_channels → finds #dev → calls discord_list_messages → writes summary)

Пример: ежедневная сводка агента Paperclip

// From an agent's prompt:
"Post the daily digest to channel 1234. Summarize the last 24h of activity
using discord_list_messages with limit=100, then format as an embed via
discord_send_message."

Обработка ошибок

Каждый инструмент возвращает пригодный для использования текстовый результат. В случае ошибки:

Error (DISCORD_50001, HTTP 403): Missing Access
Details: [...]
(This error is transient and may succeed on retry.)

MCP уже обрабатывает повторные попытки внутри для 429 (ограничения частоты) и 5xx (ошибки сервера) с экспоненциальной задержкой.


Ограничения частоты запросов (Rate limits)

В Discord есть два уровня ограничений:

  1. По маршруту — каждая конечная точка API имеет независимые корзины. Этот MCP сериализует запросы по (метод + шаблон маршрута), чтобы предотвратить превышение лимита 429.

  2. Глобальный — на бота, по всем конечным точкам. MCP глобально учитывает заголовки Retry-After.

Вам не нужно об этом думать. Если вы постоянно достигаете глобального лимита, вероятно, вы делаете что-то, что требует участия человека.


Безопасность

  • Никогда не коммитьте токен вашего бота. Этот MCP считывает его из переменной окружения DISCORD_BOT_TOKEN при запуске.

  • Используйте URL-адреса приглашений с минимальными привилегиями. Не давайте ботам права администратора, если вам нужно только «Управление сообщениями».

  • Причины в журнале аудита — все инструменты модерации принимают аргумент reason, который отображается в журнале аудита Discord. Используйте его.


Разработка

git clone https://github.com/devli13/mcp-discord.git
cd mcp-discord
npm install
npm test           # smoke tests (no live Discord calls)
npm run lint       # syntax check all files
npm start          # boot server over stdio (needs DISCORD_BOT_TOKEN)

Сопутствующий проект — входящие события

Этот MCP обрабатывает исходящие REST-вызовы (отправка, удаление, модерация). Он не поддерживает WebSocket Discord Gateway, поэтому не может реагировать на входящие события (упоминание бота через @, личные сообщения, вступление новых участников).

Для входящих событий Discord в настройке Paperclip используйте @devli13/paperclip-plugin-discord — форк @mvanhorn/paperclip-plugin-discord с произвольной маршрутизацией @упоминаний, поддержкой личных сообщений, сериализованной очередью сообщений для каждого контекста и заполнением пропущенных упоминаний.

Эти два проекта разработаны для совместной работы: плагин получает события и вызывает вашего агента; агент использует этот MCP для ответа и модерации. Используйте один или оба в зависимости от вашей настройки.

Атрибуция

См. ATTRIBUTION.md. Кратко: создано вместе с форком paperclip-plugin-discord от @mvanhorn, чья обработка Gateway вдохновила использованные здесь паттерны проектирования.

Лицензия

MIT — см. LICENSE.

Available Tools

26 tools
discord_add_reactionA

Add a reaction from the bot to a message. Emoji can be a unicode glyph (e.g. "👍") or custom-emoji string ("name:id"). Requires Add Reactions + Read Message History.

Inputs: channel_id (required), message_id (required), emoji (required).

discord_add_roleA

Add a role to a guild member. Requires Manage Roles and the target role must be below the bot's highest role.

Inputs: guild_id (required), user_id (required), role_id (required), reason.

discord_bulk_delete_messagesA

Bulk delete 2-100 messages from a channel. All messages must be less than 14 days old. Useful for raid cleanup. Requires Manage Messages permission.

Inputs: channel_id (required), message_ids (required), reason.

discord_create_threadA

Create a thread. If message_id is provided, creates a thread from that message; otherwise creates a standalone thread in the channel. auto_archive_duration is in minutes: 60, 1440, 4320, or 10080.

Inputs: channel_id (required), name (required), message_id, auto_archive_duration, +2 more.

discord_delete_messageA

Delete a single message. Requires Manage Messages for other users' messages; bot can always delete its own.

Inputs: channel_id (required), message_id (required), reason.

discord_edit_messageA

Edit a message the bot previously sent. Can edit content and embeds. Cannot edit other users' messages.

Inputs: channel_id (required), message_id (required), content, embeds.

discord_get_audit_logA

Fetch recent audit log entries. Filter by action_type (Discord AuditLogEvent enum integer) and/or user_id. Requires View Audit Log permission.

Inputs: guild_id (required), user_id, action_type, before, +1 more.

discord_get_channelB

Fetch details about a single channel — name, type, permission overwrites, parent category, rate limit, etc.

Inputs: channel_id (required).

discord_get_guildC

Fetch details for a single guild — name, icon, owner, member count, features, etc.

Inputs: guild_id (required), with_counts.

discord_get_memberC

Fetch a guild member — nickname, joined_at, roles, communication_disabled_until (timeout), etc.

Inputs: guild_id (required), user_id (required).

discord_get_messageB

Fetch a single message by ID. Useful for reading context before acting.

Inputs: channel_id (required), message_id (required).

discord_get_reactionsA

List users who reacted with a specific emoji on a message. Paginated (default 25, max 100).

Inputs: channel_id (required), message_id (required), emoji (required), limit, +1 more.

discord_kick_userA

Remove a user from the guild. They can rejoin via invite. Requires Kick Members permission.

Inputs: guild_id (required), user_id (required), reason.

discord_list_active_threadsA

List all active (non-archived) threads in a guild.

Inputs: guild_id (required).

discord_list_channelsB

List all channels in a guild (server). Includes text, voice, category, thread channels.

Inputs: guild_id (required).

discord_list_guildsA

List all guilds (servers) the bot is a member of. Useful for multi-server setups.

Inputs: limit.

discord_list_membersA

List members of a guild. Paginate with after cursor (last user ID). Requires the Server Members privileged intent on the bot.

Inputs: guild_id (required), limit, after.

discord_list_messagesA

Fetch recent messages from a channel. Paginate with before/after/around cursors. Default limit is 50, max 100.

Inputs: channel_id (required), limit, before, after, +1 more.

discord_list_rolesA

List all roles in a guild. Returns role objects sorted by position (highest first).

Inputs: guild_id (required).

discord_pin_messageA

Pin a message in a channel. Requires Manage Messages. Channels max 50 pinned messages.

Inputs: channel_id (required), message_id (required), reason.

discord_remove_reactionA

Remove a reaction. Without user_id, removes the bot's own reaction. With user_id, removes a specific user's reaction (requires Manage Messages).

Inputs: channel_id (required), message_id (required), emoji (required), user_id.

discord_remove_roleC

Remove a role from a guild member.

Inputs: guild_id (required), user_id (required), role_id (required), reason.

discord_send_messageA

Send a new message to a Discord channel. Supports plain text, embeds, replies, and allowed_mentions control. Returns the created message object including its ID.

Inputs: channel_id (required), content, embeds, reply_to_message_id, +2 more.

discord_send_typingA

Trigger the "bot is typing…" indicator in a channel for about 10 seconds. Useful before sending a long-form response so users know the bot is working.

Inputs: channel_id (required).

discord_timeout_userA

Timeout a user — they cannot send messages, react, or join voice. Up to 28 days. Pass duration_seconds=0 to remove an existing timeout. Requires Moderate Members permission.

Inputs: guild_id (required), user_id (required), duration_seconds (required), reason.

discord_unpin_messageC

Unpin a previously pinned message.

Inputs: channel_id (required), message_id (required), reason.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.6/5.0

    Scored across 26 tools

    Disambiguation4/5

    Most tools have distinct purposes targeting specific Discord resources and actions, such as send_message vs. edit_message or kick_user vs. timeout_user. However, some overlap exists: add_reaction and remove_reaction are clear, but get_reactions could be confused with list_messages for reading message content, and list_active_threads vs. create_thread might cause minor ambiguity in thread management scenarios.

    Naming Consistency5/5

    All tools follow a consistent snake_case naming pattern with a clear verb_noun structure, such as discord_send_message, discord_get_channel, and discord_list_members. The naming is predictable and uniform across all 26 tools, making it easy for agents to understand and select the appropriate tool.

    Tool Count3/5

    With 26 tools, the count is on the higher side for a Discord bot server, which may feel heavy and potentially overwhelming for agents. While Discord's API is feature-rich, this many tools could lead to decision paralysis or misselection, though it does cover a broad range of functionalities from messaging to moderation.

    Completeness4/5

    The tool set provides comprehensive coverage for core Discord bot operations, including CRUD for messages, roles, and members, as well as moderation actions like kick and timeout. Minor gaps exist, such as no tools for editing roles or managing invites, but agents can still handle most common workflows effectively without significant dead ends.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      An MCP server that allows Claude to interact with Discord by providing tools for sending/reading messages and managing server resources through Discord's API.
      19
      MIT
    • A
      license
      A
      quality
      C
      maintenance
      An MCP server that provides native Discord tools for Claude Code, enabling bidirectional communication with remote agents or humans via the Discord REST API. It allows users to send messages, read channel history, and manage reactions directly from their local environment.
      6
      3
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Comprehensive Discord MCP server with 66 tools that provides rich message context including emoji reactions, thread indicators, and attachment metadata inline. Enables AI assistants to interact with Discord servers for messaging, moderation, roles, channels, and more.
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      A comprehensive Discord MCP server enabling AI assistants to run a Discord community through 111 tools for messaging, moderation, roles, channels, forums, webhooks, and more, plus a raw REST API passthrough for full Discord API access.
      MIT