Skip to main content
Glama
reddit-mcp-server

reddit-mcp-server

by 20Youssef10
README.md
# reddit-mcp-server

[![CI](https://github.com/20Youssef10/reddit-mcp-server/actions/workflows/ci.yml/badge.svg)](https://github.com/20Youssef10/reddit-mcp-server/actions/workflows/ci.yml)

A [Model Context Protocol](https://modelcontextprotocol.io) server for Reddit — read, write, interaction and moderation tools for AI assistants, built on the official TypeScript SDK (`@modelcontextprotocol/server` v2.4.0, MCP specification **2026-07-28**, with backwards-compatible serving for 2025-era clients).

**Repository:** [20Youssef10/reddit-mcp-server](https://github.com/20Youssef10/reddit-mcp-server)

- **39 tools across four gated domains**: 14 read, 7 write, 5 interactions (vote/save/subscribe), 13 moderation
- **Safe by default**: every mutating domain is behind a feature gate, OFF by default
- **Two transports**: local-first stdio for Claude Desktop / Claude Code / any MCP host, plus a stateless remote Streamable HTTP / OAuth 2.1 resource-server mode for team use
- **5 runtime dependencies**: the MCP SDK, Zod, pino, `@modelcontextprotocol/node`, and `jose`

> **Platform warning (read this first).** Reddit is retiring the public Data API: new access requests closed 2026-10-31, unregistered apps start losing access **2027-01-12**, and all remaining public Data API access ends **March 2027**. This server is built on that API. Confirm your Reddit app is registered under the Responsible Builder Policy process before relying on it. The architecture isolates Reddit behind a swappable port/adapter so the data source can be replaced when that happens (see [docs/architecture.md](docs/architecture.md)).

## Contents

- [What this is — and what it is not](#what-this-is--and-what-it-is-not)
- [Prerequisites](#prerequisites)
- [Quick start](#quick-start)
- [Architecture at a glance](#architecture-at-a-glance)
- [Remote / HTTP deployment (Stage 6)](#remote--http-deployment-stage-6)
- [Security model](#security-model)
- [Tool catalogue (39)](#tool-catalogue-39)
- [Configuration](#configuration)
- [Login flow](#login-flow)
- [Development](#development)
- [Documentation](#documentation)
- [Community](#community)
- [License](#license)

## What this is — and what it is not

**This is** a [Model Context Protocol](https://modelcontextprotocol.io) server that exposes a curated, **read-only-by-default** set of Reddit tools to an AI assistant. Local stdio is the default and only zero-config transport; an opt-in stateless Streamable HTTP / OAuth 2.1 resource-server mode supports multiple users. Every mutating domain — write, interactions, messages, moderation — sits behind a feature gate that is **off by default**, and gated tools are hidden from `tools/list` until you enable them and re-authorise with the required scopes.

**This is not:**

- **A Reddit client or app.** It has no UI, feed reader or background polling; it answers discrete tool calls from an MCP host. It is not a general-purpose Reddit automation proxy.
- **An anonymous public API.** Every Reddit call uses a registered Reddit app's credentials; user-scoped reads and all mutations require the authorisation-code `login` flow. In HTTP mode, `/mcp` additionally requires a JWT from **your** OIDC authorization server — Reddit's opaque tokens are never MCP bearer tokens.
- **Licensed for commercial use.** No AI training, no data resale, and no commercial use without Reddit's written approval (Data API Terms). Automated voting and messaging in particular sit at the edge of the Responsible Builder Policy; keep those gates off unless you need them.
- **A long-term fixture on today's Reddit API.** The Data API is being retired (see the warning above). The port/adapter boundary is the migration seam — see [Architecture at a glance](#architecture-at-a-glance).

For answers to common "why" questions, see the [FAQ](docs/faq.md); for operational problems, see [Troubleshooting](docs/troubleshooting.md).

## Prerequisites

- **Node.js 22 LTS** (`node >= 22`, per `engines` in `package.json`). Older Node releases are not supported.

## Quick start

Clone and build from source:

```bash
git clone https://github.com/20Youssef10/reddit-mcp-server.git
cd reddit-mcp-server
npm install
npm run build
npm test          # 598 tests across 46 files; add -- --coverage for the coverage report
```

The binary is named `reddit-mcp-server`, but the **unscoped** npm name is taken
by a different project. This project's scoped name is
`@shinzero/reddit-mcp-server` (owned by the `shinzero` npm account; the GitHub
repository remains [20Youssef10/reddit-mcp-server](https://github.com/20Youssef10/reddit-mcp-server)):

```bash
npx -y @shinzero/reddit-mcp-server    # (once published)
```

**Not published yet.** The scoped package is not on the npm registry as of
v1.1.0, and npm publishing setup is still pending. Releases are intended to use
**GitHub Actions OIDC trusted publishing** — no npm automation token or
`NPM_TOKEN` environment secret is stored. The command above works only once a
release is published; see [docs/publishing.md](docs/publishing.md) for the
operator runbook. Until then, use the source install above. No npm release is
claimed here. The stdio quick start below is unchanged.

Configure credentials (from https://www.reddit.com/prefs/apps):

```bash
export REDDIT_CLIENT_ID=...        # your app's client id
export REDDIT_CLIENT_SECRET=...    # your app's client secret
npm run login                      # one-time browser authorisation (stores a 0600 refresh token)
npm run doctor                     # verify config, connectivity, scopes
```

Run it from an MCP host, e.g. Claude Desktop `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "reddit": {
      "command": "node",
      "args": ["/absolute/path/to/reddit-mcp-server/dist/index.js"],
      "env": {
        "REDDIT_CLIENT_ID": "...",
        "REDDIT_CLIENT_SECRET": "...",
        "REDDIT_USER_AGENT": "node:reddit-mcp-server:1.0.0 (by /u/your-app-account)",
        "REDDIT_ENABLE_WRITE": "true"
      }
    }
  }
}
```

Without credentials the server still starts and lists its read tools; every call returns a clear configuration error (never a crash).

## Architecture at a glance

A thin protocol layer sits over a narrow `RedditDataPort`: tools and services never touch REST details, so the Reddit data source can be swapped when the Data API retires. Both transports serve the **same** 39-tool registry — local stdio (default) and stateless HTTP with an OAuth 2.1 resource server — without changing tool contracts.

```
MCP host ──stdio / Streamable HTTP──▶ McpServer → 39-tool registry → services
                                                    (gates, scopes, budgets,
                                                     safeguards, audit, cache)
                                                         │
                                                         ▼
                                  RedditDataPort → RedditApiAdapter → RestClient
                                                              → Reddit Data API
```

- **Tool registry** — profile + gate + auth + scope filtering, one envelope seam for every result, and a typed, secret-free error taxonomy.
- **Services** — budgets, NSFW policy, write safeguards, response cache and JSONL audit; all principal-scoped in HTTP mode.
- **Port/adapter** — all Reddit endpoint knowledge lives in `src/reddit/adapter.ts`; auth endpoints are hard-coded constants (anti-spoofing).

Full design, decisions, protocol-era compatibility, Stage 6 details and deferred items: [docs/architecture.md](docs/architecture.md). The SDK/Reddit evidence behind the HTTP design: [docs/stage6-spike.md](docs/stage6-spike.md). For a guided reading order, start at [docs/index.md](docs/index.md).

## Remote / HTTP deployment (Stage 6)

`MCP_TRANSPORT=http` serves the same tool registry over **stateless Streamable HTTP** (MCP 2026-07-28) with an OAuth 2.1 resource server. The stdio quick start above is unchanged; HTTP is an additional mode.

**Prerequisites**

- Node 22 LTS (same as stdio).
- An **HTTPS reverse proxy** in front of the server. Node binds loopback by default (`127.0.0.1:3000`) and TLS is terminated at the proxy. A non-loopback bind is refused unless you explicitly set `MCP_HTTP_HOST`.
- An **OIDC authorization server (AS) with a JWKS endpoint** that you control or trust (e.g. your IdP), which issues short-lived JWTs with an `iss`, an `aud`, `exp` and `sub`. **Reddit is not that AS** — its tokens are opaque and have no JWKS. Your Reddit app credentials are still needed for upstream API calls.

**Configuration** (all `MCP_*` values are HTTP-only; the full annotated reference is [.env.example](.env.example)):

```bash
export MCP_TRANSPORT=http
export MCP_PUBLIC_URL=https://mcp.example.com        # absolute https:// URL (the advertised resource)
export MCP_OAUTH_ISSUER=https://idp.example.com       # your AS's issuer
export MCP_OAUTH_AUDIENCE=https://mcp.example.com     # expected JWT aud (RFC 8707 resource)
# export MCP_OAUTH_JWKS_URL=https://idp.example.com/.well-known/jwks.json  # optional; else discovered once from the issuer
export MCP_TOKEN_KEY_FILE=/secure/path/token-key      # 256-bit key in a 0600 file, OR MCP_TOKEN_KEY=<base64>
# export MCP_TOKEN_KEY_ID=my-key-1                    # optional public kid; defaults to a key fingerprint
# export MCP_GLOBAL_QPM=80                            # hard client-ID ceiling (<=100)
# export MCP_PER_USER_QPM=25                          # per-principal fairness (<=100)
# export MCP_HTTP_HOST=127.0.0.1                      # loopback default
# export MCP_HTTP_PORT=3000
# export MCP_ALLOWED_HOSTS=mcp.example.com            # Host / X-Forwarded-Host allow-list
# export MCP_ALLOWED_ORIGINS=https://mcp.example.com  # Origin allow-list
# export MCP_TRUST_PROXY=true                         # only if the proxy sets X-Forwarded-Host and strips client values
# export MCP_PRINCIPAL_SALT=<stable-random-string>     # stable audit digests across restarts
# Never commit real key material, secrets or salt values.
```

`GET /healthz`, `GET /readyz`, `/.well-known/oauth-protected-resource` (RFC 9728) and `/.well-known/oauth-authorization-server` are unauthenticated; `/mcp` requires `Authorization: Bearer <JWT from your AS>`. `/readyz` reports config, key, token-store and JWKS health. See [docs/architecture.md](docs/architecture.md#stage-6--remote-http-transport-implemented) for the full design.

**Two layers of authentication**

1. **L1 — your AS's JWT** authenticates the caller to this MCP server. The SDK Bearer gate plus a `jose` verifier check signature (`RS256`/`ES256`), issuer, audience, expiry and subject against your pinned JWKS; no Reddit credential is ever a MCP bearer token.
2. **L2 — the Reddit refresh token** is opaque and stays server-side. Each authenticated principal links their own Reddit account via `/oauth/start` → `/oauth/callback` (state bound to the principal; **no PKCE**, which Reddit does not document); the refresh token is encrypted at rest under that principal in the per-user store.

**Migrating an existing single-user token / unlinking a principal**

```bash
# Move the legacy 0600 auth file into the encrypted per-principal store.
# The principal id comes from your AS (issuer|subject) and is never auto-inferred.
reddit-mcp-cli migrate-auth --principal <id>            # add --remove-source to rename the old file to .migrated
# Unlink a principal's stored record (best-effort Reddit-side revocation) in http mode:
reddit-mcp-cli logout --principal <id>                  # local token file removal still happens as usual
```

Both commands print only a short `sha256:` digest, never a raw principal id or token. Without `--principal`, `logout` behaves exactly as in stdio mode (local file removal only).

See the [Stage 6 verification spike](docs/stage6-spike.md) for the SDK/Reddit API evidence and the [token revocation & credential rotation runbook](docs/runbooks/token-revocation.md) for rotation and compromise procedures.

Stage 6 operations runbooks: [key rotation](docs/runbooks/stage6-key-rotation.md), [user unlink / principal disconnect](docs/runbooks/stage6-user-unlink.md), [Reddit outage & rate-limit incident](docs/runbooks/stage6-reddit-outage.md).

## Security model

| Layer | Control |
|---|---|
| Mutating tools | Four independent gates (`REDDIT_ENABLE_WRITE`, `..._INTERACTIONS`, `..._MESSAGES`, `..._MOD`), all **off** by default; gated tools are hidden from `tools/list` entirely |
| Account actions | Authorisation-code `login` flow, refresh token stored in a `0600` file, never printed or logged; access tokens live in memory only |
| Rate limits | Token bucket at 60 QPM (Reddit free tier ceiling: 100 QPM/client), adaptive to `X-Ratelimit-*` headers, `Retry-After` honoured, jittered backoff, circuit breaker |
| Write safeguards | Hard server-side caps: 5 posts/h, 30 comments/h, 10 messages/h, minimum 15 s between content-creating actions |
| High-risk tools | `reddit_vote`, `reddit_send_message`, `reddit_delete_content`, `reddit_mod_ban_user` require an explicit `confirm: true` argument; destructive tools carry `destructiveHint` annotations so clients ask humans before executing |
| Audit | Every mutating call appended to a JSONL audit log (who, what, when, outcome) |
| NSFW content | `ask` (default) / `never` / `always` policy; listings filter with omission notes, detail tools withhold bodies until `allow_nsfw: true` |
| Prompt injection | All Reddit content is returned as quoted, clearly-bounded **data**; tool descriptions carry a standing untrusted-content warning; output budgets cap context-window usage |
| Secrets | Redaction on every log path; fault-injection tests assert zero secret leakage |

Credentials can be rotated or fully revoked at any time — see the
[token revocation & credential rotation runbook](docs/runbooks/token-revocation.md)
for both routine rotation and suspected-compromise procedures (logout, env
override removal, Reddit-side revocation, client-secret rotation, `doctor`
verification, and audit-log review). No command in that runbook prints a secret.

Stage 6 runbooks: [key rotation](docs/runbooks/stage6-key-rotation.md), [user unlink / principal disconnect](docs/runbooks/stage6-user-unlink.md), [Reddit outage & rate-limit incident](docs/runbooks/stage6-reddit-outage.md).

The tool→scope mapping in [docs/scope-matrix.md](docs/scope-matrix.md) is currently
**source-derived** (from each tool's declared `requiredScopes`); a live scope
probe with real credentials is still pending. Run `npm run build && node dist/cli.js scopes`
to enumerate Reddit's advertised scopes once credentials are available.

**Residual risks, stated honestly**

- **Vote and DM tools sit at the edge of Reddit's Responsible Builder Policy.** They are implemented (per project requirement), gated, confirmation-guarded, capped and audited — but automated voting/messaging can be classified as manipulation. Keep the gates off unless you need them, and never use them in bulk.
- Prompt injection from Reddit content cannot be fully eliminated; a convincing injection plus an inattentive human approval can still cause an unwanted (human-approved) action. Read `docs/architecture.md` §security before enabling write gates.
- No AI training, no data resale, no commercial use without Reddit's written approval (Data API Terms).

## Tool catalogue (39)

All tools return `structuredContent` validated against an `outputSchema` plus a compact text digest. Listings paginate with opaque `nextCursor` tokens.

### Read (default on; app-only token unless noted)

| Tool | Purpose |
|---|---|
| `reddit_get_me` | Identity + karma of the authorised user (user token) |
| `reddit_get_subreddit` | Subreddit metadata |
| `reddit_get_subreddit_rules` | Community rules |
| `reddit_list_posts` | Feed listings (hot/new/top/rising/controversial/best) |
| `reddit_get_post` | Post detail by id **or** reddit.com permalink |
| `reddit_get_comments` | Comment tree with depth/limit budgets |
| `reddit_search_posts` | Post search, optionally subreddit-scoped |
| `reddit_search_subreddits` | Subreddit discovery (fuzzy or exact) |
| `reddit_get_user` | User profile |
| `reddit_get_user_content` | A user's posts/comments/overview |
| `reddit_get_my_subscriptions` | Your subreddits (user token) |
| `reddit_get_my_saved` | Your saved content (user token) |
| `reddit_get_inbox` | Messages / replies / unread (user token) |
| `reddit_get_flair_options` | Post flair choices (user token) |

### Write (gate `REDDIT_ENABLE_WRITE`; `reddit_send_message` additionally `REDDIT_ENABLE_MESSAGES`)

`reddit_submit_post`, `reddit_submit_comment`, `reddit_edit_content`, `reddit_delete_content` (confirm + destructive), `reddit_send_message` (confirm), `reddit_mark_inbox_read`, `reddit_report_content`

### Interactions (gate `REDDIT_ENABLE_INTERACTIONS`)

`reddit_vote` (confirm), `reddit_save`, `reddit_unsave`, `reddit_subscribe`, `reddit_unsubscribe`

### Moderation (gate `REDDIT_ENABLE_MOD`; you must moderate the target subreddit)

`reddit_mod_list_subreddits`, `reddit_mod_get_queue`, `reddit_mod_approve`, `reddit_mod_remove` (destructive), `reddit_mod_get_log`, `reddit_mod_get_banned`, `reddit_mod_ban_user` (confirm + destructive), `reddit_mod_unban_user`, `reddit_mod_mute_user` (destructive), `reddit_mod_modmail_list`, `reddit_mod_modmail_reply`, `reddit_mod_distinguish`, `reddit_mod_set_post_moderation` (lock/sticky/NSFW/spoiler)

### Tool profiles (`REDDIT_TOOL_PROFILE`)

- `minimal` (8): the core read essentials
- `standard` (20): all 14 reads + the common safe mutations (submit post/comment, save/unsave, subscribe/unsubscribe)
- `full` (39, default): everything the gates allow

Gates filter further: a tool appears only when its gate is on, a user token exists, **and** (when scope info is recorded at login) every OAuth scope it needs was granted.

## Configuration

See [.env.example](.env.example) for the complete annotated reference (Appendix C of the research plan). Highlights:

| Variable | Default | Notes |
|---|---|---|
| `REDDIT_CLIENT_ID` / `REDDIT_CLIENT_SECRET` | — | Required for any API call; invalid values fail fast at startup |
| `REDDIT_REFRESH_TOKEN` | token file | Set directly, or run `npm run login` (recommended) |
| `REDDIT_ENABLE_WRITE` / `_INTERACTIONS` / `_MESSAGES` / `_MOD` | `false` | Feature gates |
| `REDDIT_TOOL_PROFILE` | `full` | `minimal` / `standard` / `full` |
| `REDDIT_NSFW_POLICY` | `ask` | `never` / `always` |
| `REDDIT_RATE_LIMIT_QPM` | `60` | Must be ≤ 100 |
| `REDDIT_WRITE_POSTS_PER_HOUR` | `5` | (+ comments 30/h, messages 10/h, 15 s spacing) |
| `LOG_LEVEL` | `info` | pino level; logs go to **stderr only** (stdout is the protocol) |

## Login flow

`npm run login` opens a local callback server on your `REDDIT_REDIRECT_URI` (default `http://localhost:8888/callback` — must match the app registration), prints Reddit's authorisation URL, and waits for you to approve. The scopes requested are computed from your enabled gates (least privilege — Appendix B of the plan). The refresh token is written to `~/.config/reddit-mcp-server/auth.json` (mode `0600`) with the granted scopes, so the server can hide tools whose scopes you didn't grant. `npm run logout` removes it; `npm run doctor` verifies everything end-to-end and warns about the 2027-01-12 registration deadline.

Legacy note: `REDDIT_USERNAME`/`REDDIT_PASSWORD` (script-app password grant) still work but are discouraged and may stop functioning under the new policy; use `login`.

## Development

```bash
npm run check    # typecheck (strict, tests included)
npm run lint     # ESLint (typescript-eslint; no-console enforced on the server — stdout belongs to the protocol)
npm run build    # tsc -> dist/
npm test         # full suite (unit + protocol + stdio e2e)
npm run test:coverage
npm run inspect  # official MCP Inspector: tools/list over the modern protocol era
npm run test:live  # opt-in live suite: REDDIT_LIVE_TESTS=1 with real credentials
```

Test architecture (see `docs/architecture.md`): fixtures replay Reddit's wire format through an injected fetch implementation; protocol tests drive the real `serveStdio` path over in-memory transports in **both protocol eras** (plus HTTP/protocol/multi-principal tests for Stage 6); the e2e suite spawns the built binary over real stdio. Coverage gates: ≥90% lines, ≥85% branches. **Final measurement (598 tests across 46 files, default suite; live suite excluded): 93.43% statements, 88.09% branches, 92.84% functions, 94.88% lines.** Both gates pass (lines ≥90%, branches ≥85%); the thresholded coverage command was verified twice with exit 0.

## Documentation

Start with the [documentation index](docs/index.md) for a guided reading order.

- [docs/index.md](docs/index.md) — reading guide: getting started, architecture, tools, operations, security, community
- [docs/faq.md](docs/faq.md) — concise answers to the recurring "why" questions behind the design
- [docs/troubleshooting.md](docs/troubleshooting.md) — startup, auth, rate-limit, cache, safeguard and HTTP-deployment problems
- [docs/research-and-plan.md](docs/research-and-plan.md) — the full research & planning report this implementation follows
- [docs/architecture.md](docs/architecture.md) — architecture, design decisions, deviations, Stage 6 (HTTP) implementation
- [docs/stage6-spike.md](docs/stage6-spike.md) — SDK/Reddit verification spike behind the Stage 6 design (corrected C1/C2/C3 verdicts)
- [docs/tools.md](docs/tools.md) — generated tool reference (regenerate with `npm run docs:tools`; do not hand-edit)
- [docs/scope-matrix.md](docs/scope-matrix.md) — tool→scope mapping (source-derived; live probe pending)
- [docs/runbooks/token-revocation.md](docs/runbooks/token-revocation.md) — routine rotation & suspected-compromise procedures
- [docs/runbooks/stage6-key-rotation.md](docs/runbooks/stage6-key-rotation.md) — token-store KEK, Reddit client-secret and authorization-server key rotation, with rollback
- [docs/runbooks/stage6-user-unlink.md](docs/runbooks/stage6-user-unlink.md) — unlink a principal, verify local deletion, interpret `needsRelink` and audit attribution
- [docs/runbooks/stage6-reddit-outage.md](docs/runbooks/stage6-reddit-outage.md) — readiness, circuit breaker, 429 handling and fail-open boundaries during an upstream incident
- [docs/publishing.md](docs/publishing.md) — npm publication runbook for the scoped package via GitHub Actions OIDC trusted publishing (npm setup still pending; nothing published yet)
- [CHANGELOG.md](CHANGELOG.md)

## Community

- [Contributing](CONTRIBUTING.md) — development setup, local checks, PR workflow and how to propose a new tool
- [Code of Conduct](CODE_OF_CONDUCT.md) — Contributor Covenant, standards and enforcement
- [Security policy](SECURITY.md) — supported versions, responsible disclosure and accepted residual risks
- [Support](SUPPORT.md) — where to get help and what to include in a request
- [Governance](GOVERNANCE.md) — maintainer model, decision-making and release process

Read [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request, and report security issues privately as described in [SECURITY.md](SECURITY.md) — never in a public issue.

## License

MIT

TDQS

A4.1/5.0

Scored across 9 tools

Disambiguation5/5

Each tool targets a distinct resource and action: single post, comment tree, subreddit metadata, subreddit rules, user profile, user activity, subreddit feed listing, post search, and subreddit discovery. The only close pairs (list_posts vs. search_posts, get_subreddit vs. search_subreddits) are cleanly separated by explicit 'browse a feed' vs. 'full-text search' and 'metadata' vs. 'discovery' wording.

Naming Consistency5/5

All nine tools follow a uniform reddit_<verb>_<noun> snake_case pattern (get_post, get_comments, list_posts, search_subreddits, etc.). The shared reddit_ prefix and verb vocabulary make the set predictable and easy to scan.

Tool Count5/5

Nine tools is well within the ideal 3-15 range and every tool maps to a distinct read operation on the Reddit domain. Nothing appears redundant or bolted on; the surface is tightly scoped.

Completeness3/5

The read surface is solid (posts, comments, subreddits, rules, users, searches, pagination cursors), but there are no write operations at all — no submit post, comment, vote, subscribe, or moderation actions. Several descriptions explicitly say 'use before posting or commenting', yet no such tools exist, creating dead ends for those workflows.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues