A Model Context Protocol (MCP) stdio server that exposes Discourse forum capabilities as tools and resources for AI agents. - Entry point: src/index.ts → compiled to dist/index.js (binary name: discourse-mcp) - SDK: @modelcontextprotocol/sdk - Node: >= 24 - Version: 0.2.4 (0.2.x has breaking changes from 0.1.x - JSON-only output, resources replace list tools) - Run (read‑only, recommended to start
Add this skill
npx mdskills install discourse/discourse-mcpComprehensive MCP server with extensive Discourse API coverage, flexible auth, and strong safety controls
1## Discourse MCP23A Model Context Protocol (MCP) stdio server that exposes Discourse forum capabilities as tools and resources for AI agents.45- **Entry point**: `src/index.ts` → compiled to `dist/index.js` (binary name: `discourse-mcp`)6- **SDK**: `@modelcontextprotocol/sdk`7- **Node**: >= 248- **Version**: 0.2.4 (0.2.x has breaking changes from 0.1.x - JSON-only output, resources replace list tools)910### Quick start (release)1112- **Run (read‑only, recommended to start)**1314```bash15npx -y @discourse/mcp@latest16```1718Then, in your MCP client, either:1920- Call the `discourse_select_site` tool with `{ "site": "https://try.discourse.org" }` to choose a site, or21- Start the server tethered to a site using `--site https://try.discourse.org` (in which case `discourse_select_site` is hidden).2223- **Enable writes (opt‑in, safe‑guarded)**2425```bash26npx -y @discourse/mcp@latest --allow_writes --read_only=false --auth_pairs '[{"site":"https://try.discourse.org","api_key":"'$DISCOURSE_API_KEY'","api_username":"system"}]'27```2829- **Use in an MCP client (example: Claude Desktop) — via npx**3031```json32{33 "mcpServers": {34 "discourse": {35 "command": "npx",36 "args": ["-y", "@discourse/mcp@latest"],37 "env": {}38 }39 }40}41```4243> Alternative: if you prefer a global binary after install, the package exposes `discourse-mcp`.44>45> ```json46> {47> "mcpServers": {48> "discourse": { "command": "discourse-mcp", "args": [] }49> }50> }51> ```5253## Configuration5455The server registers tools under the MCP server name `@discourse/mcp`. Choose a target Discourse site either by:5657- Using the `discourse_select_site` tool at runtime (validates via `/about.json`), or58- Supplying `--site <url>` to tether the server to a single site at startup (validates via `/about.json` and hides `discourse_select_site`).5960- **Auth**6162 - **None** by default.63 - **Admin API Keys** (require admin permissions): **`--auth_pairs '[{"site":"https://example.com","api_key":"...","api_username":"system"}]'`**64 - **User API Keys** (any user can generate): **`--auth_pairs '[{"site":"https://example.com","user_api_key":"...","user_api_client_id":"..."}]'`**65 - **HTTP Basic Auth** (for sites behind a reverse proxy): Add `http_basic_user` and `http_basic_pass` to any `auth_pairs` entry. This is useful for Discourse sites protected by HTTP Basic Authentication at the reverse proxy level.66 - You can include multiple entries in `auth_pairs`; the matching entry is used for the selected site. If both `user_api_key` and `api_key` are provided for the same site, `user_api_key` takes precedence.6768- **Write safety**6970 - Writes are disabled by default.71 - Write tools (`discourse_create_post`, `discourse_create_topic`, `discourse_create_category`, `discourse_update_topic`, `discourse_create_user`, `discourse_update_user`, `discourse_upload_file`, `discourse_save_draft`, `discourse_delete_draft`) are only registered when `--allow_writes` AND not `--read_only`.72 - Write tools require a matching `auth_pairs` entry for the selected site; otherwise they return an error.73 - A ~1 req/sec rate limit is enforced for write actions.7475- **Flags & defaults**7677 - `--read_only` (default: true)78 - `--allow_writes` (default: false)79 - `--timeout_ms <number>` (default: 15000)80 - `--concurrency <number>` (default: 4)81 - `--log_level <silent|error|info|debug>` (default: info)82 - `debug`: Shows all HTTP requests, responses, and detailed error information83 - `info`: Shows retry attempts and general operational messages84 - `error`: Shows only errors85 - `silent`: No logging output86 - `--show_emails` (default: false). includes emails in user tools. Requires admin access87 - `--tools_mode <auto|discourse_api_only|tool_exec_api>` (default: auto)88 - `--site <url>`: Tether MCP to a single site and hide `discourse_select_site`.89 - `--default-search <prefix>`: Unconditionally prefix every search query (e.g., `tag:ai order:latest`).90 - `--max-read-length <number>`: Maximum characters returned for post content (default 50000). Applies to `discourse_read_post` and per-post content in `discourse_read_topic`. The tools prefer `raw` content by requesting `include_raw=true`.91 - `--allowed_upload_paths <paths>`: Comma-separated list or JSON array of directories allowed for local file uploads. Required to enable local file uploads in `discourse_upload_file`. Example: `--allowed_upload_paths "/home/user/images,/tmp/uploads"` or `--allowed_upload_paths '["/home/user/images"]'`92 - `--transport <stdio|http>` (default: stdio): Transport type. Use `stdio` for standard input/output (default), or `http` for Streamable HTTP transport (stateless mode with JSON responses).93 - `--port <number>` (default: 3000): Port to listen on when using HTTP transport.94 - `--cache_dir <path>` (reserved)95 - `--profile <path.json>` (see below)9697- **Profile file** (keep secrets off the command line)9899```json100{101 "auth_pairs": [102 {103 "site": "https://try.discourse.org",104 "api_key": "<redacted>",105 "api_username": "system"106 },107 {108 "site": "https://example.com",109 "user_api_key": "<user_api_key>",110 "user_api_client_id": "<client_id>"111 },112 {113 "site": "https://protected.example.com",114 "api_key": "<redacted>",115 "api_username": "system",116 "http_basic_user": "username",117 "http_basic_pass": "password"118 }119 ],120 "read_only": false,121 "allow_writes": true,122 "show_emails": true,123 "log_level": "info",124 "tools_mode": "auto",125 "site": "https://try.discourse.org",126 "default_search": "tag:ai order:latest",127 "max_read_length": 50000,128 "transport": "stdio",129 "port": 3000,130 "allowed_upload_paths": ["/home/user/images", "/tmp/uploads"]131}132```133134Run with:135136```bash137node dist/index.js --profile /absolute/path/to/profile.json138```139140Flags still override values from the profile.141142- **Remote Tool Execution API (optional)**143144 - With `tools_mode=auto` (default) or `tool_exec_api`, the server discovers remote tools via GET `/ai/tools` after you select a site (or immediately at startup if `--site` is provided) and registers them dynamically. Set `--tools_mode=discourse_api_only` to disable remote tool discovery.145146- **Networking & resilience**147148 - Retries on 429/5xx with backoff (3 attempts).149 - Lightweight in‑memory GET cache for selected endpoints.150151- **Privacy**152 - Secrets are redacted in logs. Errors are returned as human‑readable messages to MCP clients.153154## MCP Resources155156Resources provide static/semi-static read-only data via URI addressing. Use these instead of tools for listing operations.157158- **discourse://site/categories**159160 - List all categories with hierarchy and permissions161 - Output: `{ categories: [{id, name, slug, pid, read_restricted, topic_count, post_count, perms}], meta: {total} }`162 - `perms` is array of `{gid, perm}` where perm: 1=full, 2=create_post, 3=readonly163 - **Note**: `perms` is only populated with admin/moderator auth. Without admin auth, only `read_restricted` boolean is available.164165- **discourse://site/tags**166167 - List all tags with usage counts168 - Output: `{ tags: [{id, name, count}], meta: {total} }`169170- **discourse://site/groups**171172 - List all groups with visibility, interaction levels, and access settings173 - Output: `{ groups: [{id, name, automatic, user_count, vis, members_vis, mention, msg, public_admission, public_exit, allow_membership_requests}], meta: {total} }`174 - **Levels** (0-4): 0=public, 1=logged_on_users, 2=members, 3=staff, 4=owners175 - **Use case**: Resolve `gid` values from category permissions to group names, replicate group settings during migrations176177- **discourse://chat/channels**178179 - List all public chat channels180 - Output: `{ channels: [{id, title, slug, status, members_count, description}], meta: {total} }`181182- **discourse://user/chat-channels**183184 - List user's chat channels (public + DMs) with unread/mention counts185 - Output: `{ public_channels: [...], dm_channels: [...], meta: {total} }`186 - Requires authentication187188- **discourse://user/drafts**189 - List user's drafts190 - Output: `{ drafts: [{draft_key, sequence, title, category_id, created_at, reply_preview}], meta: {total} }`191 - Requires authentication192193## Tools194195Built‑in tools (always present unless noted). All tools return **strict JSON** (no Markdown).196197- `discourse_search`198 - Input: `{ query: string; max_results?: number (1–50, default 10) }`199 - Output: `{ results: [{id, slug, title}], meta: {total, has_more} }`200- `discourse_read_topic`201 - Input: `{ topic_id: number; post_limit?: number (1–50, default 5); start_post_number?: number }`202 - Output: `{ id, title, slug, category_id, tags, posts_count, posts: [{id, post_number, username, created_at, raw}], meta }`203- `discourse_read_post`204 - Input: `{ post_id: number }`205 - Output: `{ id, topic_id, topic_slug, post_number, username, created_at, raw, truncated }`206- `discourse_get_user`207 - Input: `{ username: string }`208 - Output: `{ id, username, name, trust_level, created_at, bio, admin, moderator }`209- `discourse_list_user_posts`210 - Input: `{ username: string; page?: number (0-based); limit?: number (1–50, default 30) }`211 - Output: `{ posts: [{id, topic_id, post_number, slug, title, created_at, excerpt, category_id}], meta: {page, limit, has_more} }`212- `discourse_filter_topics`213 - Input: `{ filter: string; page?: number; per_page?: number (1–50) }`214 - Output: `{ results: [{id, slug, title}], meta: {page, limit, has_more} }`215 - Query language (succinct): key:value tokens separated by spaces; category/categories (comma = OR, `=category` = without subcats, `-` prefix = exclude); tag/tags (comma = OR, `+` = AND) and tag_group; status:(open|closed|archived|listed|unlisted|public); personal `in:` (bookmarked|watching|tracking|muted|pinned); dates: created/activity/latest-post-(before|after) with `YYYY-MM-DD` or relative days `N`; numeric: likes[-op]-(min|max), posts-(min|max), posters-(min|max), views-(min|max); order: activity|created|latest-post|likes|likes-op|posters|title|views|category with optional `-asc`; free text terms are matched.216- `discourse_get_chat_messages`217 - Input: `{ channel_id: number; page_size?: number (1–50, default 50); target_message_id?: number; direction?: "past" | "future"; target_date?: string (ISO 8601) }`218 - Output: `{ channel_id, messages: [{id, username, created_at, message, edited, thread_id, in_reply_to_id}], meta }`219- `discourse_get_draft`220 - Input: `{ draft_key: string; sequence?: number }`221 - Output: `{ draft_key, sequence, found, data: {title, reply, category_id, tags, action} }`222- `discourse_save_draft` (only when writes enabled; see Write safety)223 - Input: `{ draft_key: string; reply: string; title?: string; category_id?: number; tags?: string[]; sequence?: number (default 0); action?: "createTopic" | "reply" | "edit" | "privateMessage" }`224 - Output: `{ draft_key, sequence, saved }`225- `discourse_delete_draft` (only when writes enabled; see Write safety)226 - Input: `{ draft_key: string; sequence: number }`227 - Output: `{ draft_key, deleted }`228- `discourse_create_post` (only when writes enabled; see Write safety)229 - Input: `{ topic_id: number; raw: string (<= 30k chars); author_username?: string }`230 - Output: `{ id, topic_id, post_number }`231- `discourse_create_topic` (only when writes enabled; see Write safety)232 - Input: `{ title: string; raw: string (<= 30k chars); category_id?: number; tags?: string[]; author_username?: string }`233 - Output: `{ id, topic_id, slug, title }`234- `discourse_update_topic` (only when writes enabled; see Write safety)235 - Input: `{ topic_id: number; title?: string; category_id?: number; tags?: string[]; featured_link?: string; original_title?: string; original_tags?: string[] }`236 - Output: `{ success, topic_id, updated_fields, topic: {id, title, slug, category_id, tags, featured_link} }`237- `discourse_list_users` (requires admin API key)238 - Input: `{ query?: "active"|"new"|"staff"|"suspended"|"silenced"|"pending"|"staged"; filter?: string; order?: "created"|"last_emailed"|"seen"|"username"|"trust_level"|"days_visited"|"posts"; asc?: boolean; page?: number }`239 - Output: `{ users: [{id, username, name, email, avatar_template, trust_level, created_at, last_seen_at, admin, moderator, suspended, silenced}], meta: {page, has_more} }`240 - Note: Returns ~100 users per page (Discourse's fixed page size). `avatar_template` contains `{size}` placeholder - replace with pixel size (e.g., 120) to get avatar URL241- `discourse_create_user` (only when writes enabled; see Write safety)242 - Input: `{ username: string (1-20 chars); email: string; name: string; password: string; active?: boolean; approved?: boolean; upload_id?: number }`243 - Output: `{ success, username, name, email, active, avatar_updated, message, avatar_error? }`244 - Note: If `upload_id` is provided but avatar update fails, `avatar_error` contains the error message245- `discourse_update_user` (only when writes enabled; see Write safety)246 - Input: `{ username: string; name?: string; bio_raw?: string; location?: string; website?: string; title?: string; date_of_birth?: string; locale?: string; profile_background_upload_url?: string; card_background_upload_url?: string; upload_id?: number }`247 - Output: `{ success, username, updated_fields, avatar_updated, user: {...}, avatar_error? }`248 - Note: If `upload_id` is provided but avatar update fails, `avatar_error` contains the error message249- `discourse_upload_file` (only when writes enabled; see Write safety)250 - Input: `{ upload_type: "avatar"|"profile_background"|"card_background"|"composer"; image_data?: string (base64); url?: string; filename?: string; user_id?: number }`251 - Output: `{ id, url, short_url, short_path, original_filename, extension, width, height, filesize, human_filesize }`252 - Constraints:253 - Provide exactly one of: `image_data` (requires `filename`), remote HTTP(S) URL, or absolute local file path254 - `user_id` is required for avatar/profile_background/card_background uploads255 - Local file uploads require `--allowed_upload_paths` configuration (security: prevents arbitrary file reads)256 - Note: Use `short_url` (e.g., `upload://abc123.png`) to embed images in posts.257- `discourse_create_category` (only when writes enabled; see Write safety)258 - Input: `{ name: string; color?: hex; text_color?: hex; emoji?: string; icon?: string; parent_category_id?: number; description?: string }`259 - Output: `{ id, slug, name }`260- `discourse_select_site` (hidden when `--site` is provided)261 - Input: `{ site: string }`262 - Output: `{ site, title }`263264## Development265266- **Requirements**: Node >= 24, `pnpm`.267268- **Install / Build / Typecheck / Test**269270```bash271pnpm install272pnpm typecheck273pnpm build274pnpm test275```276277- **Run locally (with source maps)**278279```bash280pnpm build && pnpm dev281```282283- **Project layout**284285 - Server & CLI: `src/index.ts`286 - HTTP client: `src/http/client.ts`287 - Tool registry: `src/tools/registry.ts`288 - Resource registry: `src/resources/registry.ts`289 - Built‑in tools: `src/tools/builtin/*`290 - Remote tools: `src/tools/remote/tool_exec_api.ts`291 - JSON helpers: `src/util/json_response.ts`292 - Logging/redaction: `src/util/logger.ts`, `src/util/redact.ts`293294- **Testing notes**295296 - Tests run with Node’s test runner against compiled artifacts (`dist/test/**/*.js`). Ensure `pnpm build` before `pnpm test` if invoking scripts individually.297298- **Publishing (optional)**299300 - The package is published as `@discourse/mcp` and exposes a `bin` named `discourse-mcp`. Prefer `npx @discourse/mcp@latest` for frictionless usage.301302- **Conventions**303 - All outputs are JSON-only for reliable programmatic parsing by agents.304 - Be careful with write operations; keep them opt‑in and rate‑limited.305306See `AGENTS.md` for additional guidance on using this server from agent frameworks.307308## Examples309310### Quick Start with User API Key (No Admin Required)311312```bash313# Step 1: Generate a User API Key314npx @discourse/mcp@latest generate-user-api-key \315 --site https://discourse.example.com \316 --save-to profile.json317318# Step 2: Visit the authorization URL shown, approve the request, and paste the payload319320# Step 3: Run the MCP server with your new key321npx @discourse/mcp@latest --profile profile.json --allow_writes --read_only=false322```323324### Other Examples325326- Read‑only session against `try.discourse.org`:327328```bash329npx -y @discourse/mcp@latest --log_level debug330# In client: call discourse_select_site with {"site":"https://try.discourse.org"}331```332333- Tether to a single site:334335```bash336npx -y @discourse/mcp@latest --site https://try.discourse.org337```338339- Create a post with Admin API Key (writes enabled):340341```bash342npx -y @discourse/mcp@latest --allow_writes --read_only=false --auth_pairs '[{"site":"https://try.discourse.org","api_key":"'$DISCOURSE_API_KEY'","api_username":"system"}]'343```344345- Create a post with User API Key (writes enabled, no admin required):346347```bash348npx -y @discourse/mcp@latest --allow_writes --read_only=false --auth_pairs '[{"site":"https://try.discourse.org","user_api_key":"'$DISCOURSE_USER_API_KEY'"}]'349```350351- Create a category (writes enabled):352353```bash354npx -y @discourse/mcp@latest --allow_writes --read_only=false --auth_pairs '[{"site":"https://try.discourse.org","api_key":"'$DISCOURSE_API_KEY'","api_username":"system"}]'355# In your MCP client, call discourse_create_category with for example:356# { "name": "AI Research", "color": "0088CC", "text_color": "FFFFFF", "description": "Discussions about AI research" }357```358359- Create a topic (writes enabled):360361```bash362npx -y @discourse/mcp@latest --allow_writes --read_only=false --auth_pairs '[{"site":"https://try.discourse.org","api_key":"'$DISCOURSE_API_KEY'","api_username":"system"}]'363# In your MCP client, call discourse_create_topic, for example:364# { "title": "Agentic workflows", "raw": "Let's discuss agent workflows.", "category_id": 1, "tags": ["ai","agents"] }365```366367- Run with HTTP transport (on port 3000):368369```bash370npx -y @discourse/mcp@latest --transport http --port 3000 --site https://try.discourse.org371# Server will start on http://localhost:3000372# Health check: http://localhost:3000/health373# MCP endpoint: http://localhost:3000/mcp374```375376- Connect to a site behind HTTP Basic Auth:377378```bash379npx -y @discourse/mcp@latest --auth_pairs '[{"site":"https://protected.example.com","api_key":"'$DISCOURSE_API_KEY'","api_username":"system","http_basic_user":"username","http_basic_pass":"password"}]' --site https://protected.example.com380```381382## Authentication383384### Admin API Keys vs User API Keys385386This MCP server supports two types of Discourse API authentication:3873881. **Admin API Keys** (`api_key` + `api_username`)389390 - Require admin/moderator permissions to generate391 - Created via Admin Panel → API → New API Key392 - Can perform all operations including user/category creation393 - Use headers: `Api-Key` and `Api-Username`3943952. **User API Keys** (`user_api_key` + optional `user_api_client_id`)396 - Can be generated by any user (no admin required)397 - User-specific permissions and rate limits398 - Ideal for personal use and non-admin operations399 - Use headers: `User-Api-Key` and `User-Api-Client-Id`400 - Auto-expire after 180 days of inactivity (configurable per site)401 - Learn more: https://meta.discourse.org/t/user-api-keys-specification/48536402403### Obtaining a User API Key404405#### Easy Method: Built-in Generator (Recommended)406407This package includes a convenient command to generate User API Keys:408409```bash410# Interactive mode - follow the prompts411npx @discourse/mcp@latest generate-user-api-key --site https://discourse.example.com412413# Save directly to a profile file414npx @discourse/mcp@latest generate-user-api-key --site https://discourse.example.com --save-to profile.json415416# Specify custom scopes417npx @discourse/mcp@latest generate-user-api-key --site https://discourse.example.com --scopes "read,write,notifications"418419# Get help420npx @discourse/mcp@latest generate-user-api-key --help421```422423The command will:4244251. Generate an RSA key pair4262. Display an authorization URL for you to visit4273. Prompt you to paste the encrypted payload after authorization4284. Decrypt and display your User API Key4295. Optionally save it to a profile file430431#### Manual Method432433User API Keys require an OAuth-like flow documented at https://meta.discourse.org/t/user-api-keys-specification/48536. Key steps:4344351. Generate a public/private key pair4362. Request authorization via `/user-api-key/new` with your public key, application name, client ID, and requested scopes4373. User approves the request (after login if needed)4384. Discourse returns an encrypted payload with the User API Key4395. Decrypt using your private key and use the key in your configuration440441You can also manually create User API Keys via the Discourse UI (if enabled by the site):442443- Visit your user preferences → Security → API444- Or use third-party tools that implement the User API Key flow445446## FAQ447448- **Why is `create_post` missing?** You're in read‑only mode. Enable writes as described above.449- **Can I disable remote tool discovery?** Yes, run with `--tools_mode=discourse_api_only`.450- **Can I avoid exposing `discourse_select_site`?** Yes, start with `--site <url>` to tether to a single site.451- **Time outs or rate limits?** Increase `--timeout_ms`, and note built‑in retry/backoff on 429/5xx.452- **Should I use Admin API Keys or User API Keys?** Use User API Keys for personal use (no admin required). Use Admin API Keys only when you need admin-level operations or are setting up a system-wide integration.453- **Getting "fetch failed" errors?** Run with `--log_level debug` to see detailed error information including:454 - The exact URL being requested455 - HTTP status codes and response bodies456 - Network-level errors (DNS, SSL/TLS, connectivity issues)457 - Retry attempts and timing458 - Timeout diagnostics459
Full transparency — inspect the skill content before installing.