Skip to main content
Glama
discord-mcp

discord-mcp

by 20Youssef10
README.md
# discord-mcp

A [Model Context Protocol](https://modelcontextprotocol.io) server for Discord communities: 50 tools, 4 prompts and 6 resource templates for guilds, channels, messages, members, roles, scheduled events, audit logs, analytics, scheduled announcements and the bot account itself (identity, global user lookup, opt-in direct messages, leave guild, prune, bulk delete, reactions, crossposts).

It is platform neutral: standard Node.js (22.13 or newer), stdio or self-hosted Streamable HTTP, SQLite or in-memory storage, no vendor-specific runtime. It runs on Linux, macOS and Windows, bare metal, a container or any Node host.

## How it is organised

| Layer | Package | Role |
| --- | --- | --- |
| Contracts | `packages/contracts` | Tool catalog (Zod schemas), permission bits, ports, error codes |
| Adapters | `packages/discord-rest`, `packages/storage`, `packages/discord-gateway` | Discord REST v10 client, SQLite / memory storage, Gateway worker |
| Domain | `packages/policy`, `packages/audit`, `packages/analytics`, `packages/automation` | Authorization chain, audit trail, daily metrics, scheduled announcements |
| Core | `packages/core` | Tool executor, 37 handlers, resources, prompts, job runner |
| Transport | `packages/mcp`, `packages/runtime` | MCP server factory, HTTP pipeline, auth, configuration, composition root |
| Apps | `apps/mcp-stdio`, `apps/mcp-http`, `apps/discord-gateway` | Entry points |

The design is described in [docs/plan-and-architecture.md](docs/plan-and-architecture.md), the reasons behind it in [docs/decisions.md](docs/decisions.md), and day-to-day operation in [docs/runbook.md](docs/runbook.md).

## Security model in one paragraph

Every tool call passes the same chain: authenticated caller → MCP scope → guild allowlist → profile ceiling → feature flag → channel allowlist → per-caller overrides → confirmation for destructive actions → the bot's own Discord permissions → the Discord API. An empty guild allowlist denies every guild. The default profile is `read_only`, moderation is off, `@everyone` and mass role mentions are denied, and a confirmation token bound to the exact arguments is required before any destructive tool runs. Write tools additionally need a verified bot identity: if Discord rejects the token or cannot be reached, they abort with `DISCORD_AUTH_INVALID` or `DISCORD_API_UNAVAILABLE` instead of skipping a check; read tools are unaffected. Stored per-principal policy rows can only narrow scopes (`*` in a row never widens them), and OIDC principals never receive the `*` wildcard. `tools/list` is filtered by the caller's MCP scopes for visibility; the policy engine and executor remain the authorization boundary. There is no raw Discord proxy tool. Audit records never contain the bot token or message content.

## Quick start

```bash
npm ci
cp .env.example .env          # fill in DISCORD_BOT_TOKEN
npm run check                 # typecheck, lint, format check, tests
```

Invite the bot with only the permissions your profile needs (read tools: View Channels, Read Message History; `community_ops`: Send Messages, Create Public Threads, Pin Messages, Manage Channels for channel edits, Create Events / Manage Events for events; `admin`: Manage Roles, Moderate Members, Kick Members, Ban Members, View Audit Log).

### stdio (Claude Desktop, Claude Code, Cursor, other local clients)

```json
{
  "mcpServers": {
    "discord": {
      "command": "node",
      "args": ["/absolute/path/to/discord-mcp/apps/mcp-stdio/dist/index.js"],
      "env": {
        "DISCORD_BOT_TOKEN": "...",
        "DISCORD_ALLOWED_GUILD_IDS": "123456789012345678",
        "DISCORD_ALLOWED_CHANNEL_IDS": "234567890123456789",
        "DISCORD_DEFAULT_PROFILE": "community_ops",
        "STORAGE_PATH": "/home/you/.discord-mcp/state.sqlite"
      }
    }
  }
}
```

For development from the TypeScript sources: `npm run dev:stdio`.

### Streamable HTTP

```bash
DISCORD_BOT_TOKEN=... DISCORD_ALLOWED_GUILD_IDS=123 STORAGE_PATH=/var/lib/discord-mcp/state.sqlite \
MCP_HTTP_HOST=0.0.0.0 MCP_HTTP_PORT=3000 MCP_HTTP_PUBLIC_URL=https://mcp.example.com/mcp \
MCP_AUTH_MODE=static MCP_STATIC_TOKENS=/etc/discord-mcp/tokens.json \
node apps/mcp-http/dist/index.js
```

Client configuration for HTTP clients (for example Claude Code):

```bash
claude mcp add --transport http discord https://mcp.example.com/mcp --header "Authorization: Bearer <token>"
```

`MCP_AUTH_MODE=none` is refused unless the host is loopback. Static tokens are a JSON array `[{"token":"<at least 16 chars>","principal":"alice","scopes":["discord.guilds.read","discord.channels.read"]}]` or a path to a file with that JSON. `MCP_AUTH_MODE=oidc` accepts access tokens from your identity provider (`MCP_OIDC_ISSUER`, optional `MCP_OIDC_AUDIENCE`); the server publishes the protected-resource metadata under `/.well-known/oauth-protected-resource`. Callers authenticated by OIDC never receive the `*` wildcard.

### Docker

```bash
docker build -t discord-mcp .
docker run -p 3000:3000 --env-file .env -v discord-mcp-data:/data discord-mcp
```

## Configuration reference

| Variable | Default | Meaning |
| --- | --- | --- |
| `DISCORD_BOT_TOKEN` | required | Bot token; sent only to `https://discord.com/api/v10` |
| `DISCORD_APPLICATION_ID` | unset | Application id, informational |
| `DISCORD_DEFAULT_PROFILE` | `read_only` | Ceiling for every caller: `read_only`, `community_ops`, `admin` |
| `DISCORD_ALLOWED_GUILD_IDS` | empty | Guild allowlist; empty denies all |
| `DISCORD_ALLOWED_CHANNEL_IDS` | empty | Channel allowlist; empty allows every channel of an allowed guild |
| `DISCORD_ENFORCE_GUILD_ALLOWLIST` | `true` | `false` disables the guild allowlist (only for a single trusted guild) |
| `DISCORD_ENABLE_MODERATION` | `false` | Timeout, kick, ban, unban, prune |
| `DISCORD_ENABLE_DIRECT_MESSAGES` | `false` | Direct-message tools (personal data; admin profile only) |
| `DISCORD_MASS_MENTION_MODE` | `deny` | `allow` passes `@everyone` and mass mentions through |
| `MCP_HTTP_HOST` / `MCP_HTTP_PORT` / `MCP_HTTP_PATH` | `127.0.0.1` / `3000` / `/mcp` | HTTP bind address and endpoint |
| `MCP_HTTP_PUBLIC_URL` | derived | External endpoint URL (behind a proxy) |
| `MCP_HTTP_ALLOWED_HOSTS` / `MCP_HTTP_ALLOWED_ORIGINS` | loopback values | Extra accepted `Host`/`Origin` **hostnames** (no scheme, no port; DNS rebinding protection) |
| `MCP_HTTP_MAX_BODY_BYTES` / `MCP_HTTP_REQUEST_TIMEOUT_MS` | `1048576` / `15000` | Request limits |
| `HTTP_RUN_JOBS` | `true` | Run the announcement scheduler in the HTTP process |
| `MCP_AUTH_MODE` | `none` | `none` (loopback only), `static`, `oidc` |
| `MCP_STATIC_TOKENS` | unset | Static bearer tokens (JSON or file path) |
| `MCP_OIDC_ISSUER` / `MCP_OIDC_JWKS_URI` / `MCP_OIDC_AUDIENCE` | unset | OIDC verification |
| `MCP_LOCAL_SCOPES` | `*` | Scopes of the local operator identity |
| `STORAGE_PATH` | empty | SQLite file; empty or `:memory:` keeps state in memory |
| `AUDIT_RETENTION_DAYS` / `ANALYTICS_RETENTION_DAYS` | `90` / `365` | Retention |
| `CONFIRMATION_TTL_SECONDS` | `120` | Lifetime of a confirmation token (single use) |
| `AUTOMATION_MAX_SCHEDULE_AHEAD_HOURS` | `720` | How far an announcement may be scheduled |
| `AUTOMATION_POLL_INTERVAL_MS` | `1000` | Scheduler tick |
| `ENABLE_GATEWAY` | `false` | Required for the Gateway worker app |
| `ENABLE_INTENT_MESSAGE_CONTENT` / `ENABLE_INTENT_GUILD_MEMBERS` | `false` | Privileged intents (also enabled in the developer portal) |
| `ENABLE_INTENT_GUILD_PRESENCES` | refused | The server does not use presence data |
| `LOG_LEVEL` / `LOG_FORMAT` | `info` / `json` | Logs go to stderr only |

Unknown values, an empty token, `none` auth on a non-loopback host, static mode without tokens and `http://` OIDC issuers on a non-loopback address all stop the process with a list of problems.

## Tools

### Account-level and completion tools (13, on top of the 37 guild tools)

Account-level tools act on the bot account, not on a server, so the guild allowlist does not apply
to them; MCP scopes, the profile ceiling and feature flags still do. Direct-message tools hold
personal data and stay hidden until `DISCORD_ENABLE_DIRECT_MESSAGES=true`, and they also need the
admin profile. Every destructive tool follows the standard confirmation flow.

| Tool | Risk | Profile | Scope |
| --- | --- | --- | --- |
| `discord_get_current_user` | read | read_only | `discord.account.read` |
| `discord_get_user` (any user by ID) | read | read_only | `discord.account.read` |
| `discord_list_dm_channels` | read | admin + DM flag | `discord.dm.read` |
| `discord_create_dm` | write | admin + DM flag | `discord.dm.write` |
| `discord_send_dm_message` | write | admin + DM flag | `discord.dm.write` |
| `discord_leave_guild` | destructive | admin + confirmation | `discord.account.write` |
| `discord_prune_members` | destructive | admin + confirmation + moderation flag | `discord.moderation.kick` |
| `discord_bulk_delete_messages` | destructive | admin + confirmation | `discord.messages.write` |
| `discord_delete_role` | destructive | admin + confirmation | `discord.roles.write` |
| `discord_crosspost_message` | write | community_ops | `discord.messages.write` |
| `discord_follow_announcement_channel` | write | admin | `discord.channels.write` |
| `discord_add_reaction` / `discord_remove_reaction` | write | community_ops | `discord.messages.write` |

Limits the tools enforce before Discord rejects the call: bulk delete takes 2-100 messages that are
at most 14 days old (a Discord API limit); prune uses 1-30 inactive days and by default only removes
members with no roles; crosspost only works in announcement channels and only for messages the bot
itself posted; follow requires Manage Webhooks on the target channel; the reaction tools only ever
touch the bot's own reactions.


Read: `list_guilds`, `get_guild`, `get_guild_metrics`, `get_audit_log`, `list_channels`, `get_channel`, `list_messages`, `get_message`, `get_member`, `list_members`, `list_roles`, `get_role`, `list_scheduled_events`, `get_activity_summary`, `get_growth_summary`, `list_announcement_jobs`.
Community: `send_message`, `edit_message`, `delete_message`, `create_thread`, `pin_message`, `create_channel`, `edit_channel`, `delete_channel`, `create_scheduled_event`, `edit_scheduled_event`, `delete_scheduled_event`, `schedule_announcement`, `cancel_announcement_job`.
Admin: `create_role`, `edit_role`, `assign_role`, `remove_role`, `timeout_member`, `kick_member`, `ban_member`, `unban_member`.
(All names carry the `discord_` prefix.) Every tool returns `{ ok, data | error, confirmation? }` and validates its output against a schema; text read from Discord is returned with an untrusted-content note.

## Client compatibility

The server speaks stdio and the MCP Streamable HTTP transport (spec 2026-07-28) through the
official TypeScript SDK, which negotiates a mutually compatible protocol version with older clients, so it works with current clients: Claude Desktop and Claude Code over
stdio, and Claude for the web, Cursor, VS Code or any MCP 2025-06-18+ HTTP client over Streamable
HTTP. Clients that only speak the removed HTTP+SSE transport are not supported; they need an
upgrade, not a server change.

Beyond the wire protocol, for agent and client compatibility:

- the `initialize` result carries `instructions` that explain the envelope format, the gate order
  and the confirmation flow, so an LLM that never read this README still behaves correctly;
- every tool has a `title`, a `description`, an `inputSchema`, an `outputSchema` and MCP annotations
  (`readOnlyHint`, `destructiveHint`, `idempotentHint`), so clients can sort and warn without
  calling anything;
- every result is JSON with `structuredContent` (the envelope: `ok`, then `data` or `error` with a
  stable code and a readable message), and tool failures are `isError` results rather than protocol
  errors, so agents can read them and recover;
- `tools/list` is deterministic (sorted by name): 50 tools total, 15 visible at the default
  `read_only` profile, and clients can page the list;
- prompts expose argument metadata, and resources are standard `discord://` templates.

## Verification

This delivery was checked on Linux with Node v24.22.2. `npm run check` is green in all four stages: the TypeScript compiler reports 0 errors, eslint reports 0 problems, Prettier finds no differences, and vitest passes 139 of 139 tests across 29 files (about 64.5% statement coverage), including the security, protocol, retention, tools/list and shutdown suites. `npm run build` bundles all three apps with esbuild, and both transports answer smoke requests: stdio and HTTP both return `instructions` and list tools (15 at the default `read_only` profile), and HTTP serves `GET /healthz`, returns `401` for a wrong bearer token and completes `initialize` and `tools/list` with a static token. No request was sent to the live Discord API: the REST client is tested against a mock `fetch` and the executor against a fake REST port, so real rate limiting, permissions and intents are covered only as far as the documented behaviour goes.

Run `npm run check`. Individually: `npm run typecheck`, `npm run lint`, `npm run format:check`, `npm test`; `npm run build` and `npm run test:coverage` are separate. After building, `node apps/mcp-http/dist/index.js --run-due-jobs` applies pending migrations and processes due announcements once. `npm run storage:migrate` migrates a SQLite file without starting a server.

## Scope limits

No live Discord call is made by the test-suite (a fake REST port and a mock `fetch` stand in for Discord). The Gateway worker needs the privileged intents enabled in the developer portal. Analytics are daily aggregates stored locally; nothing leaves the host except requests to the Discord API.