Skip to main content
Glama
cord-mcp
by rayakame
README.md
<h1 align="center">cord-mcp</h1>

<p align="center">
  <strong>Full-featured Discord Bot MCP server with live Gateway state caching and embedded SQLite FTS5 search.</strong>
</p>

<p align="center">
  <a href="https://pypi.org/project/cord-mcp/"><img src="https://img.shields.io/pypi/v/cord-mcp" alt="PyPI"></a>
  <a href="https://pypi.org/project/cord-mcp/"><img src="https://img.shields.io/pypi/pyversions/cord-mcp" alt="Python versions"></a>
  <a href="https://github.com/rayakame/cord-mcp/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/rayakame/cord-mcp/ci.yml?branch=main&label=CI" alt="CI"></a>
  <a href="https://codecov.io/gh/rayakame/cord-mcp"><img src="https://codecov.io/gh/rayakame/cord-mcp/branch/main/graph/badge.svg" alt="Coverage"></a>
  <a href="https://github.com/microsoft/pyright"><img src="https://img.shields.io/badge/pyright-strict-blue" alt="pyright strict"></a>
  <a href="https://github.com/astral-sh/ty"><img src="https://img.shields.io/badge/ty-checked-46ebe1" alt="ty checked"></a>
  <a href="https://github.com/astral-sh/ruff"><img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json" alt="Ruff"></a>
  <a href="https://github.com/rayakame/cord-mcp/blob/main/LICENSE"><img src="https://img.shields.io/pypi/l/cord-mcp" alt="License: MIT"></a>
</p>

`cord-mcp` connects MCP clients (Claude Desktop, Cursor, VS Code, or custom HTTP/SSE hosts) to Discord using official Discord Bot tokens. Built on a streamlined, Discord API v10-complete [hikari](https://github.com/hikari-py/hikari) core (`cord_mcp.discord`), it pairs zero-REST Gateway caching with an embedded **SQLite WAL + FTS5 BM25** full-text search index so clients can search, summarize, write, and moderate across entire servers in milliseconds.

---

## Why `cord-mcp`?

- **77 Tools, 6 Resources & 5 Prompts — Zero Feature Gaps**: Covers server discovery, channel trees, client-side effective permission calculation, high-throughput message reading, full-text search, **Components V2**, embeds, polls, file/text/base64 attachments, message forwarding, threads, forums, roles, webhooks, soundboard, scheduled events, stage instances, onboarding, audit logs, and AutoMod.
- **Instant Full-Text Search for Discord Bots (`SQLite WAL + FTS5`)**: Discord's official Bot API does not expose a guild-wide `/messages/search` endpoint. `cord-mcp` indexes live Gateway events (`MESSAGE_CREATE`, partial `MESSAGE_UPDATE`, reactions, and policy-compliant hard deletes on `MESSAGE_DELETE`) alongside an incremental multi-page batch backfiller (`backfill_channel_messages` / `backfill_guild_messages`) with BM25 ranking across message text, embeds, Components V2 `TextDisplay` trees, polls, attachment filenames, and forwarded snapshots.
- **Unified `msgspec` Discord API v10 & Native MCP Core**: Strips unneeded bot-framework weight (UDP voice/DAVE audio streaming, slash-command webhook HTTP servers, OAuth2 web flows, monetization) and unifies both the Discord v10 engine/cache (`cord_mcp.discord`) and the MCP server (`cord_mcp.mcp`) natively on **`msgspec.Struct` + `aiohttp`** (`stdio`, `streamable-http`, and `sse` with zero `attrs`, `orjson`, `pydantic`, `starlette`, or `uvicorn` runtime dependencies).
- **Safe by Default**:
  - `@everyone`, `@here`, and `@role` mentions are blocked on every outbound tool unless explicitly opted into per call.
  - Automatic Gateway intent fallback (`CORD_MCP_INTENTS=auto`) gracefully handles close code `4014` if privileged intents are not enabled in the Discord Developer Portal.
  - Built-in `--read-only` (`CORD_MCP_READ_ONLY=true`) and server allowlisting (`CORD_MCP_ALLOWED_GUILDS`).
  - All 64-bit Snowflake IDs are accepted and returned as strings to prevent IEEE-754 precision loss in JSON/JavaScript hosts.

## Architecture

```mermaid
flowchart LR
    Host["MCP Host (stdio / HTTP / SSE)"] <--> MCP["cord_mcp.mcp (77 Tools, 6 Resources, 5 Prompts)"]
    MCP --> Engine["CordMCPEngine (Guardrails, Backfill, Converters)"]
    Engine <--> Cache["GatewayBot + Stateful Cache"]
    Engine <--> REST["RESTClient v10 (Rate-Limit Buckets)"]
    Engine <--> Store["SQLite WAL + FTS5 BM25 Store"]
    Cache -- "Live Create / Edit / Delete Sync" --> Store
    REST -- "Auto-Index & Watermark Backfill" --> Store
```

---

## Quick Start

### Option A: Always-On Docker Daemon *(recommended for multi-client & 24/7 indexing)*

Running `cord-mcp` as a persistent background container keeps **one** Discord Gateway connection, rate-limit state, and warm SQLite FTS5 index alive 24/7 so multiple MCP clients can connect instantly over `streamable-http`:

```sh
cp .env.example .env
# Edit .env and set DISCORD_TOKEN (plus optional CORD_MCP_HTTP_BEARER_TOKEN)
docker compose up -d
```

Or run the prebuilt multi-arch image (`linux/amd64`, `linux/arm64`) directly from GHCR:

```sh
docker run -d --name cord-mcp --restart unless-stopped \
  -p 127.0.0.1:8000:8000 \
  -v cord-mcp-data:/data \
  -e DISCORD_TOKEN="your_bot_token" \
  -e CORD_MCP_HTTP_BEARER_TOKEN="your_optional_bearer_secret" \
  ghcr.io/rayakame/cord-mcp:latest
```

### Option B: Run directly with `uvx` (`stdio`, Python 3.15+)

```sh
DISCORD_TOKEN="your_bot_token" uvx cord-mcp serve
```

### Option C: Install from source with `uv`

```sh
git clone https://github.com/rayakame/cord-mcp.git
cd cord-mcp
uv sync

# Inspect the full MCP surface or verify your bot token
uv run cord-mcp tools
DISCORD_TOKEN="your_bot_token" uv run cord-mcp check-token
```

---

## MCP Client Configuration

### Connecting to the Docker / Streamable HTTP Daemon

```json
{
  "mcpServers": {
    "cord-mcp": {
      "url": "http://127.0.0.1:8000/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_OPTIONAL_BEARER_SECRET"
      }
    }
  }
}
```

### Claude Desktop / Cursor / VS Code (`stdio`)

Using `uvx` (published package):

```json
{
  "mcpServers": {
    "cord-mcp": {
      "command": "uvx",
      "args": ["cord-mcp", "serve"],
      "env": {
        "DISCORD_TOKEN": "YOUR_DISCORD_BOT_TOKEN"
      }
    }
  }
}
```

Or from a local checkout:

```json
{
  "mcpServers": {
    "cord-mcp": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/cord-mcp", "cord-mcp", "serve"],
      "env": {
        "DISCORD_TOKEN": "YOUR_DISCORD_BOT_TOKEN",
        "CORD_MCP_MODE": "gateway",
        "CORD_MCP_INTENTS": "auto"
      }
    }
  }
}
```

### Read-Only & Guild-Scoped Profile

```json
{
  "mcpServers": {
    "cord-mcp-readonly": {
      "command": "uvx",
      "args": ["cord-mcp", "serve", "--read-only"],
      "env": {
        "DISCORD_TOKEN": "YOUR_DISCORD_BOT_TOKEN",
        "CORD_MCP_ALLOWED_GUILDS": "123456789012345678,987654321098765432"
      }
    }
  }
}
```

### Standalone Streamable HTTP / SSE Server

```sh
DISCORD_TOKEN="YOUR_DISCORD_BOT_TOKEN" cord-mcp serve --transport streamable-http --host 127.0.0.1 --port 8000 --http-bearer-token "YOUR_SECRET"
```

---

## Discord Bot Setup

In the [Discord Developer Portal](https://discord.com/developers/applications):

1. **Bot -> Privileged Gateway Intents**:
   - **Message Content Intent**: **Required** to read and index message content, embeds, and Components V2 across server channels.
   - **Server Members Intent**: Recommended for full member caching, role resolution, and thread member details.
   - **Presence Intent**: Optional (enables `list_presences`; `CORD_MCP_INTENTS=auto` automatically negotiates without it if disabled).
2. **Recommended Bot Permissions**:
   - **Read & Search**: `VIEW_CHANNEL`, `READ_MESSAGE_HISTORY`
   - **Messaging & Collaboration**: `SEND_MESSAGES`, `SEND_MESSAGES_IN_THREADS`, `EMBED_LINKS`, `ATTACH_FILES`, `ADD_REACTIONS`, `SEND_POLLS`, `CREATE_PUBLIC_THREADS`, `PIN_MESSAGES`
   - **Administration & Moderation**: `MANAGE_MESSAGES`, `MANAGE_CHANNELS`, `MANAGE_THREADS`, `MANAGE_ROLES`, `MANAGE_WEBHOOKS`, `MANAGE_GUILD_EXPRESSIONS`, `MANAGE_EVENTS`, `KICK_MEMBERS`, `BAN_MEMBERS`, `MODERATE_MEMBERS`, `VIEW_AUDIT_LOG`, `MANAGE_GUILD`

---

## Configuration Reference

| Environment Variable | CLI Flag | Default | Description |
| :--- | :--- | :--- | :--- |
| `CORD_MCP_TOKEN` / `DISCORD_TOKEN` | `--token` | *(required)* | Official Discord Bot token (`Bot ` prefix stripped automatically if present). |
| `CORD_MCP_MODE` | `--mode` | `gateway` | `gateway` (live WebSocket cache + real-time FTS5 sync + REST) or `rest` (stateless REST + local SQLite store). |
| `CORD_MCP_INTENTS` | `--intents` | `auto` | `auto`, `all`, `unprivileged`, or comma-separated `Intents` names. |
| `CORD_MCP_DB_PATH` | `--db-path` | `~/.local/share/cord-mcp/messages.db` | SQLite WAL + FTS5 database path, or `:memory:` for ephemeral sessions. |
| `CORD_MCP_READ_ONLY` | `--read-only` | `false` | Blocks all write, administrative, and moderation tools when `true`. |
| `CORD_MCP_ALLOWED_GUILDS` | `--allowed-guilds` | *(all)* | Comma-separated allowlist of Guild Snowflake IDs. |
| `CORD_MCP_STARTUP_TIMEOUT` | — | `10.0` | Seconds to wait for initial Gateway handshake (`0` = no timeout). |
| `CORD_MCP_MAX_BACKFILL_PER_CALL` | — | `5000` | Maximum messages fetched from Discord REST in a single backfill call. |
| `CORD_MCP_AUTO_INDEX_GATEWAY` | — | `true` | Index live Gateway messages, edits, reactions, and deletes into SQLite FTS5. |
| `CORD_MCP_AUTO_INDEX_REST` | — | `true` | Index messages fetched or created via REST into SQLite FTS5. |
| `CORD_MCP_ALLOW_USER_MENTIONS` | — | `true` | Default `allow_user_mentions` setting on outbound messages. |
| `CORD_MCP_ALLOW_REPLIED_USER_MENTION` | — | `true` | Default `mention_replied_user` setting on replies. |
| `CORD_MCP_TRANSPORT` | `--transport` | `stdio` | `stdio`, `streamable-http`, or `sse`. |
| `CORD_MCP_HOST` / `CORD_MCP_PORT` | `--host` / `--port` | `127.0.0.1` / `8000` | Bind address for `streamable-http` and `sse` transports (`GET /health` exposed for probes). |
| `CORD_MCP_HTTP_BEARER_TOKEN` | `--http-bearer-token` | *(unset)* | Optional `Authorization: Bearer <token>` secret required on `streamable-http` and `sse` endpoints. |
| `CORD_MCP_LOG_LEVEL` | `--log-level` | `WARNING` | Stderr logging verbosity (`DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`). |

### CLI Subcommands

```sh
cord-mcp serve [options]          # Run the MCP server (default command)
cord-mcp tools [--json]           # Print all 77 tools, 6 resources, and 5 prompts
cord-mcp stats [--db-path ...]    # Inspect local SQLite FTS5 index & channel sync watermarks
cord-mcp check-token [--token ..] # Validate bot token and list accessible guilds
```

---

## Declarative Components V2 Example

`send_message`, `edit_message`, `create_forum_post`, and `execute_webhook` accept declarative **Components V2** layouts directly and set `MessageFlag.IS_COMPONENTS_V2` automatically:

```json
{
  "channel_id": "123456789012345678",
  "components": [
    {
      "type": "container",
      "accent_color": "#5865F2",
      "components": [
        {
          "type": "section",
          "components": [
            { "type": "text_display", "content": "## Release v2.0 Live\nAll systems operational." }
          ],
          "accessory": {
            "type": "link_button",
            "label": "Changelog",
            "url": "https://example.com/changelog"
          }
        },
        { "type": "separator", "divider": true, "spacing": "small" },
        { "type": "text_display", "content": "- Gateway latency: **18ms**\n- FTS5 index: **ready**" }
      ]
    }
  ]
}
```

---

## Complete MCP Surface

<details>
<summary><strong>1. Discovery & Server Context (15 Read Tools)</strong></summary>

- `get_bot_status` — Runtime mode, bot user, negotiated Gateway intents, cache metrics, and SQLite FTS5 store stats.
- `list_guilds` — Accessible guilds with member, channel, and role counts.
- `get_guild_overview` — Full server profile, features, boost tier, vanity URL, and system/rules channels.
- `get_channel_tree` — Hierarchical category -> channel -> active thread tree (with optional per-channel bot permissions).
- `get_channel_details` — Channel/thread/forum/voice/stage metadata, tags, slowmode, and permission overwrites.
- `get_effective_permissions` — Exact Discord API v10 effective permissions for any member (or the bot) at guild or channel/thread scope.
- `list_roles` — Guild role hierarchy with colors, flags, and permission bitfields.
- `list_members` — List or prefix-search guild members, filter by role, and attach cached presences.
- `get_member_info` — Member roles, join/boost timestamps, timeout state, base permissions, presence, and voice state.
- `get_user_info` — Global Discord user profile lookup (cache-first, REST fallback).
- `list_presences` — Cached online/idle/dnd statuses and rich activities.
- `list_voice_states` — Active voice and stage participants across a guild or channel.
- `list_emojis_and_stickers` — Custom guild emojis and stickers.
- `list_soundboard_sounds` — Guild custom soundboard sounds and/or built-in Discord default sounds.
- `get_guild_widget` — Guild widget settings and live public widget data.
</details>

<details>
<summary><strong>2. Message Reading, Context & SQLite FTS5 Search (10 Read Tools)</strong></summary>

- `get_message` — Fetch a single message (embeds, Components V2, poll, attachments, reactions, forwarded snapshots).
- `read_channel_messages` — Multi-page chronological message reader (`1..1000` messages, `before`/`after`/`around`, auto-indexed into FTS5).
- `get_message_context` — Surrounding temporal message window (`around`) plus multi-hop parent reply-chain resolution.
- `list_pinned_messages` — Paginated channel pins with pin timestamps (`before_iso` cursor).
- `list_reaction_users` — Users who reacted with a Unicode or custom emoji.
- `get_poll_results` — Poll answer tallies and per-answer voter lists.
- `search_messages` — Local SQLite FTS5 BM25 search (`"exact phrases"`, `prefix*`, `-negation`, diacritic-aware, punctuation-safe) with structured filters (`guild_id`, `channel_ids`, `author_ids`, `exclude_author_ids`, `include_bots`, `mentions_user_id`, `mentions_role_id`, `reply_to_id`, `before`/`after`, `is_pinned`, `has_attachments`, `has_embeds`, `has_links`, `has_poll`, `has_components`, `is_forwarded`, and `auto_backfill_if_empty`).
- `backfill_channel_messages` — Incremental, backward, or full batch backfill of a channel/thread into SQLite FTS5.
- `backfill_guild_messages` — Guild-wide backfill across readable channels and active threads.
- `get_message_store_stats` — SQLite FTS5 index counts, DB size, and per-channel sync watermarks.
</details>

<details>
<summary><strong>3. Messaging, Components V2 & Reactions (13 Write Tools)</strong></summary>

- `send_message` — Send markdown, replies, embeds, file/text/base64/URL attachments, polls, stickers, or Components V2 layouts with safe-mention defaults.
- `forward_message` — Forward any message (`MessageReferenceType.FORWARD`) to another channel or thread.
- `edit_message` — Edit bot messages (content, embeds, Components V2 preserving `IS_COMPONENTS_V2`, attachments).
- `delete_message` / `bulk_delete_messages` — Delete single or bulk (`<14` days) messages with audit `reason` and automatic FTS5 purge.
- `pin_message` / `unpin_message` — Pin or unpin messages with audit `reason`.
- `add_reaction` / `remove_reaction` / `clear_reactions` — Manage Unicode and custom `<:name:id>` reactions.
- `end_poll` — Immediately expire/finalize an active poll authored by the bot.
- `trigger_typing` — Trigger the channel typing indicator.
- `crosspost_message` — Publish announcement (`GUILD_NEWS`) messages to following servers.
</details>

<details>
<summary><strong>4. Channels, Categories, Forums & Threads (12 Tools)</strong></summary>

- `create_channel` / `edit_channel` / `delete_channel` / `reorder_channels` — Full lifecycle for text, announcement, voice, stage, category, forum, and media channels.
- `set_channel_permission_overwrite` / `delete_channel_permission_overwrite` — Role and member permission overwrites (accepting both Hikari and Discord API permission names).
- `list_threads` / `create_thread` / `edit_thread` — Active and archived threads, standalone or message-attached creation, archiving, locking, and pinning (`ChannelFlag.PINNED`).
- `create_forum_post` — Forum and media post creation with case-insensitive tag name/ID resolution, embeds, Components V2, attachments, or polls.
- `list_thread_members` / `manage_thread_membership` — Inspect thread members or join/leave/add/remove users.
</details>

<details>
<summary><strong>5. Guild Administration, Roles, Webhooks & Events (16 Tools)</strong></summary>

- `edit_guild` — Server name, description, verification/filter levels, and system/rules/AFK channels.
- `create_role` / `edit_role` / `delete_role` / `update_member_roles` — Role CRUD, hierarchy reordering, and member role assignment.
- `manage_custom_emoji` / `manage_guild_sticker` / `manage_soundboard` — Custom server expressions and soundboard CRUD + playback.
- `list_webhooks` / `manage_webhook` / `execute_webhook` — Webhook CRUD and rich execution (custom persona, thread targeting, Components V2, embeds, polls, safe mentions).
- `list_invites` / `manage_invite` — Invite inspection, creation (including `target_user_ids` and `role_ids`), and deletion.
- `list_scheduled_events` / `manage_scheduled_event` — Stage, voice, and external scheduled event management and subscriber lists.
- `manage_stage_and_onboarding` — Live Stage Instance CRUD and Guild Onboarding prompt/mode management.
</details>

<details>
<summary><strong>6. Moderation, Audit Logs & AutoMod (11 Tools)</strong></summary>

- `kick_member` / `ban_member` / `bulk_ban_members` / `unban_user` / `list_bans` — Single and atomic bulk moderation (`bulk_ban_users` up to 200 users) with `X-Audit-Log-Reason`.
- `timeout_member` — Apply or clear communication timeouts.
- `edit_member_moderation` — Nicknames, server voice mute/deaf states, and voice channel move/disconnect.
- `prune_inactive_members` — Dry-run prune estimation (`dry_run=True` default) or execution.
- `read_audit_logs` — Paginated guild audit log reader with actor and `AuditLogEventType` filtering.
- `list_automod_rules` / `manage_automod_rule` — AutoMod rule CRUD across keyword, regex, preset, mention-spam, and member-profile triggers and all action types.
</details>

<details>
<summary><strong>MCP Resources (6) & Prompts (5)</strong></summary>

**Resources:**
- `discord://status`
- `discord://guilds`
- `discord://guilds/{guild_id}/overview`
- `discord://guilds/{guild_id}/channels`
- `discord://channels/{channel_id}/recent`
- `discord://channels/{channel_id}/pins`

**Prompts:**
- `summarize_channel_activity`
- `investigate_moderation_incident`
- `audit_server_permissions`
- `search_server_knowledge`
- `draft_rich_announcement`
</details>

---

## Development

See [CONTRIBUTING.md](CONTRIBUTING.md) for the full contributor and release guide.

```sh
uv sync --group dev
uv run --group nox nox
```

## License

[MIT](LICENSE) — Copyright (c) 2026 Rayakame, incorporating derived components from [hikari-py/hikari](https://github.com/hikari-py/hikari) under the MIT License.