### Example Startup Log Messages Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/server-initialization.md Illustrates the expected log output during server initialization, categorized by sections like [Setup]. ```log [Setup] Reddit client initialized [Setup] Authentication mode: auto [Setup] Using anonymous Reddit API (~10 req/min) [Setup] No authentication required - ready to use! [Setup] Read-only mode (no user credentials) [Setup] For write operations, set REDDIT_USERNAME and REDDIT_PASSWORD [Setup] Safe mode: off (explicitly disabled — ensure compliance with Reddit's Responsible Builder Policy) [Setup] Bot disclosure: off [Setup] For Reddit policy compliance, consider REDDIT_BOT_DISCLOSURE=auto [Setup] Starting in stdio mode ``` -------------------------------- ### Development Setup Commands Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CONTRIBUTING.md Run these commands to set up the development environment, install dependencies, build the project, run tests, and format/lint the code. ```bash pnpm install pnpm build pnpm test pnpm format pnpm lint ``` -------------------------------- ### Install Reddit MCP Server via NPX Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/README.md Run this command to start the server without a local installation. It's useful for quick testing or integration. ```bash npx reddit-mcp-server ``` -------------------------------- ### Build and Start Server (npx) Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CLAUDE.md Builds the project and starts the server using npx. ```bash pnpm start ``` -------------------------------- ### Correct Release Workflow Example Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CLAUDE.md A step-by-step guide for performing a correct release, ensuring version consistency across multiple files before committing and pushing. ```bash # 1. Make sure check:versions passes BEFORE bumping pnpm check:versions # 2. Bump package.json without committing/tagging yet npm version patch --no-git-tag-version # 3. Hand-edit server.json (both version fields) and manifest.json to match # Or use sed/jq — the file structure is stable # 4. Verify, validate, then commit + tag together pnpm check:versions pnpm validate git add package.json server.json manifest.json pnpm-lock.yaml git commit -m "x.y.z" git tag "v$(node -p "require('./package.json').version")" git push --follow-tags ``` -------------------------------- ### Quick Start: Anonymous Mode Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CLAUDE.md Run the server in anonymous mode without any setup, suitable for testing basic functionality. ```bash export REDDIT_AUTH_MODE=anonymous npx reddit-mcp-server ``` -------------------------------- ### Setup Reddit Client Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/server-initialization.md Asynchronously sets up the Reddit client by reading environment variables, validating configuration, and initializing the client. This function should be called before starting the server. ```typescript async function setupRedditClient() { // ... validation and config building ... } // Called in main() before starting server await setupRedditClient() ``` -------------------------------- ### Create Post Example Response Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Example of a successful response after creating a Reddit post. This confirms the post details and link. ```markdown # Post Created Successfully ## Post Details - Title: My first post - Subreddit: r/typescript - Type: self - Link: https://reddit.com/r/typescript/comments/abc123/... Your post has been successfully submitted to r/typescript. ``` -------------------------------- ### Install Dependencies Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CLAUDE.md Installs project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Quick Start: Authenticated Mode with OAuth Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CLAUDE.md Enable higher rate limits by configuring OAuth credentials and running the server. ```bash export REDDIT_AUTH_MODE=auto export REDDIT_CLIENT_ID=your_client_id export REDDIT_CLIENT_SECRET=your_client_secret npx reddit-mcp-server ``` -------------------------------- ### Development Build and Run Commands Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/INDEX.md Commands for installing dependencies, running the development server, and executing tests. ```bash pnpm install pnpm dev # Build and run MCP inspector pnpm test # Run tests ``` -------------------------------- ### MCP Error Response Format Example Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md This example demonstrates the error response format used by MCP tools. Errors are returned as strings starting with 'Error:', not thrown. ```text Error: [error message] ``` ```text Error: Failed to get user info for nonexistent_user: HTTP 404 ``` -------------------------------- ### Version Sync Script Example Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CLAUDE.md An example of a 'version' npm lifecycle script that can auto-sync version numbers across JSON files and stage them for git. ```json "scripts": { "version": "tsx scripts/sync-versions.ts && git add server.json manifest.json" } ``` -------------------------------- ### MCP Tool Registration Example Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md This example shows how tools are registered in the FastMCP server, including their name, description, parameters defined with Zod schema, and an execute handler. ```typescript 1. Has a unique `name` (used for invocation) 2. Has a `description` (shown in UI) 3. Defines `parameters` using Zod schema (runtime validation) 4. Has an `execute` handler (async function) ``` -------------------------------- ### CLI Options Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/README.md Command-line interface options for checking version, getting help, and generating OAuth tokens. ```bash npx reddit-mcp-server --version # Show version npx reddit-mcp-server --help # Show help npx reddit-mcp-server --generate-token # Generate OAuth token for HTTP mode ``` -------------------------------- ### Quick Start: Safe Mode for Writes Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CLAUDE.md Configure the server with safe mode enabled for write operations, using provided username and password. ```bash export REDDIT_USERNAME=your_username export REDDIT_PASSWORD=your_password export REDDIT_SAFE_MODE=standard npx reddit-mcp-server ``` -------------------------------- ### Start FastMCP Server Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/server-initialization.md Initiates the FastMCP server startup process after setting up the Reddit client. The server can be started in either HTTP streaming mode or standard input/output (stdio) mode, based on the TRANSPORT_TYPE environment variable. ```typescript async function main() { await setupRedditClient() const useHttp = process.env.TRANSPORT_TYPE === "httpStream" || process.env.TRANSPORT_TYPE === "http" const port = parseInt(process.env.PORT ?? "3000") const host = process.env.HOST ?? "127.0.0.1" if (useHttp) { console.error(`[Setup] Starting HTTP server on ${host}:${port}`) await server.start({ transportType: "httpStream", httpStream: { port, host, endpoint: "/mcp", }, }) console.error(`[Setup] HTTP server ready at http://${host}:${port}/mcp`) console.error(`[Setup] SSE endpoint available at http://${host}:${port}/sse`) } else { console.error("[Setup] Starting in stdio mode") await server.start({ transportType: "stdio", }) } } void main().catch(console.error) ``` -------------------------------- ### Docker Quick Start Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/README.md Pull the latest Docker image and run the MCP server as a detached container with port mapping and environment variables. ```bash # Pull and run docker pull ghcr.io/jordanburke/reddit-mcp-server:latest docker run -d \ --name reddit-mcp \ -p 3000:3000 \ -e REDDIT_CLIENT_ID=your_client_id \ -e REDDIT_CLIENT_SECRET=your_client_secret \ -e REDDIT_SAFE_MODE=standard \ ghcr.io/jordanburke/reddit-mcp-server:latest ``` -------------------------------- ### Reply to Post Example Response Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Example of a successful response after replying to a Reddit post or comment. This confirms the comment details. ```markdown # Reply Posted Successfully ## Comment Details - Posted to: t3_abc123 - Author: u/myusername - Comment ID: def456 Your reply has been successfully posted. ``` -------------------------------- ### Start HTTP Server with OAuth Protection Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/README.md Enable OAuth protection for the HTTP server by setting environment variables and generating a token. ```bash export OAUTH_ENABLED=true export OAUTH_TOKEN=$(npx reddit-mcp-server --generate-token | tail -1) TRANSPORT_TYPE=httpStream node dist/index.js ``` -------------------------------- ### Example Error Messages for Server Startup Validation Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/configuration.md Illustrates common error messages that may appear on server startup due to invalid configuration values or missing required credentials. ```bash [Error] Invalid REDDIT_AUTH_MODE: invalid_value [Error] Valid options are: auto, authenticated, anonymous [Error] Authenticated mode requires REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET ``` -------------------------------- ### Full MCP Server Configuration Example Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/README.md This JSON configuration shows how to set up the reddit-mcp-server with specific environment variables for Reddit API access and safe mode. ```json { "mcpServers": { "reddit": { "command": "npx", "args": ["reddit-mcp-server"], "env": { "REDDIT_CLIENT_ID": "your_client_id", "REDDIT_CLIENT_SECRET": "your_client_secret", "REDDIT_USERNAME": "your_username", "REDDIT_PASSWORD": "your_password", "REDDIT_SAFE_MODE": "standard" } } } } ``` -------------------------------- ### Example: Delete Post Success Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md This is an example of a success message after a post has been permanently deleted. It includes a warning that the action cannot be undone. ```markdown # Post Deleted Successfully The post t3_abc123 has been permanently deleted from Reddit. **Note**: This action cannot be undone. The post content has been removed and cannot be recovered. ``` -------------------------------- ### Example Request with OAuth Protection Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CLAUDE.md Send a request to the HTTP server with OAuth protection enabled, including the Authorization header. ```bash curl -H "Authorization: Bearer your-token" http://localhost:3000/mcp ``` -------------------------------- ### Start Server in Default Stdio Mode Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/server-initialization.md Commands to start the FastMCP server in its default stdio mode, which listens on stdin/stdout using the MCP JSON-RPC protocol. This mode is commonly used by clients like Claude Desktop and Cursor. ```bash npx reddit-mcp-server # or node dist/index.js # or pnpm serve ``` -------------------------------- ### ResponseCache Initialization and Set Example Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/response-cache.md Demonstrates how to initialize ResponseCache with a byte budget and store a response using the set method. It also shows how to retrieve the cached response later. ```typescript const cache = new ResponseCache({ maxBytes: 50 * 1024 * 1024 }) const url = "https://oauth.reddit.com/r/typescript/hot.json?limit=10" const responseBody = '{"data": {...}}' // Store response cache.set(url, responseBody, 200) // Later, call get() to retrieve const cached = cache.get(url) // => { body: responseBody, status: 200 } (while not expired) // Update same URL (old entry evicted first) cache.set(url, newBody, 200) ``` -------------------------------- ### Example Markdown for Browsing Subreddit Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Demonstrates the markdown output for browsing subreddit posts, displaying them according to the specified sort order (e.g., 'hot'). ```markdown # hot posts from r/programming (hot) ### 1. New language feature announcement - Author: u/alice - Score: 3,000 (92.5% upvoted) - Comments: 450 - Posted: 2024-06-13 08:00:00 - Link: https://reddit.com/r/programming/comments/abc123/... ``` -------------------------------- ### Cache Miss Example (Expired Entry) Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/response-cache.md Illustrates a cache miss due to an expired entry. The example uses a mocked 'now' function to simulate time passing beyond the entry's expiration. ```typescript const now = 1000000 const cache = new ResponseCache({ maxBytes: 50 * 1024 * 1024, now: () => now, }) // Set at time 1000000 cache.set(url, body, 200) // Entry expiresAt: 1000000 + 60000 = 1060000 // Query at time 1060001 (after expiry) const result = cache.get(url) // now() returns 1060001 // => undefined (expired, entry deleted) ``` -------------------------------- ### Example Subreddit Information Response Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Illustrates the markdown format for detailed subreddit information, including overview, analysis, and engagement tips. ```markdown # Subreddit Information: r/typescript ## Overview - Name: r/typescript - Title: TypeScript - Subscribers: 500,000 - Active Users: 2,500 ## Community Analysis - Well-established community - Highly active community with strong engagement - Mature subreddit with established culture ## Engagement Tips - Post during peak hours for maximum visibility - Quick responses recommended due to high activity ``` -------------------------------- ### Log Setup Status and Test Connection Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/server-initialization.md Logs the initialization status and tests the Reddit API connection, especially for OAuth. Exits with an error if the connection fails. ```typescript console.error("[Setup] Reddit client initialized") console.error(`[Setup] Authentication mode: ${authMode}`) if (authMode === "anonymous" || !hasCredentials) { console.error("[Setup] Using anonymous Reddit API (~10 req/min)") console.error("[Setup] No authentication required - ready to use!") } else { console.error("[Setup] Testing Reddit API connection...") const isConnected = await client.checkAuthentication() if (!isConnected) { console.error("[Error] ✗ Failed to connect to Reddit API") console.error("[Error] Please check your REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET") process.exit(1) } console.error("[Setup] ✓ Reddit API connection successful") console.error("[Setup] Using OAuth Reddit API (60-100 req/min)") } ``` -------------------------------- ### Example Reddit Search Results Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Illustrates the markdown format for displaying Reddit search results, including post details and links. ```markdown # Reddit Search Results for: "rust programming" Sorted by: new | Time: week | Type: link ### 1. Getting started with Rust - Subreddit: r/rust - Author: u/bob_smith - Score: 800 (88.0% upvoted) - Comments: 120 - Posted: 2024-06-12 14:00:00 - Link: https://reddit.com/r/rust/comments/abc123/... ``` -------------------------------- ### Load Environment Variables Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/server-initialization.md Loads environment variables from a .env file if present, in addition to process.env. Use this at the start of your application. ```typescript import dotenv from "dotenv" dotenv.config({ quiet: true }) ``` -------------------------------- ### Run Reddit MCP Server in Zero-Setup Anonymous Mode Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/configuration.md Starts the Reddit MCP Server with no environment variables required, enabling anonymous, read-only access with a limited rate of approximately 10 requests per minute. ```bash # No env vars needed npx reddit-mcp-server # Read-only access only # Rate limit: ~10 req/min ``` -------------------------------- ### Register Tool with Server Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/server-initialization.md Adds a tool to the FastMCP server instance. Each tool includes a unique name, a description, Zod-defined parameters, and an asynchronous execution handler. This example shows the registration of a 'get_user_info' tool. ```typescript server.addTool({ name: "get_user_info", description: "Get detailed information about a Reddit user…", parameters: z.object({ username: z.string().describe("The Reddit username (without u/ prefix)"), }), execute: async (args) => { const client = unwrapClient() // ... tool implementation ... }, }) // ... 15 more tools added similarly ... ``` -------------------------------- ### Example Markdown for Reddit Post Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Illustrates the expected markdown format for the response of the get_reddit_post function, including post details, content, stats, and engagement analysis. ```markdown # Post from r/typescript ## Post Details - Title: How to use generics effectively - Type: self - Author: u/torvalds ## Content This is the full text content of the post... ## Stats - Score: 2,500 - Upvote Ratio: 95.0% - Comments: 250 ## Engagement Analysis - Highly successful post with strong community approval - Generated significant discussion ``` -------------------------------- ### Minimal Cache Configuration Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/response-cache.md Configures a ResponseCache with a maximum byte limit of 10 megabytes. This is a basic setup for a moderately sized cache. ```typescript const cache = new ResponseCache({ maxBytes: 10 * 1024 * 1024 }) ``` -------------------------------- ### Run Reddit MCP Server (Stdio) Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/overview.md Starts the Reddit MCP Server using the default stdio transport. This is commonly used by MCP clients like Claude Desktop and Cursor. ```bash npx reddit-mcp-server ``` ```bash node dist/index.js ``` -------------------------------- ### Cache Hit Example Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/response-cache.md Demonstrates a successful cache hit scenario where a previously stored response is retrieved. The entry is moved to the most-recently-used position. ```typescript const cache = new ResponseCache({ maxBytes: 50 * 1024 * 1024 }) const url = "https://oauth.reddit.com/r/typescript/hot.json" const body = '{"data": {...}}' cache.set(url, body, 200) // Cache: { url: { body, status: 200, expiresAt: now + 60000, bytes: ... } } // currentBytes: ~50 (depends on actual string length) const result = cache.get(url) // => { body, status: 200 } // Entry is moved to end (most-recently-used) ``` -------------------------------- ### Configure Reddit MCP Server for Strict Production Setup Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/configuration.md Sets up a strict production environment for the Reddit MCP Server, including authenticated access, specific transport settings, and OAuth security. ```bash export REDDIT_AUTH_MODE="authenticated" export REDDIT_CLIENT_ID="$REDDIT_CLIENT_ID" export REDDIT_CLIENT_SECRET="$REDDIT_CLIENT_SECRET" export REDDIT_USERNAME="$REDDIT_USERNAME" export REDDIT_PASSWORD="$REDDIT_PASSWORD" export REDDIT_SAFE_MODE="strict" export REDDIT_BOT_DISCLOSURE="auto" export REDDIT_CACHE="on" export REDDIT_CACHE_MAX_MB="100" export TRANSPORT_TYPE="httpStream" export PORT="3000" export HOST="127.0.0.1" export OAUTH_ENABLED="true" export OAUTH_TOKEN="$(openssl rand -hex 16)" node dist/index.js ``` -------------------------------- ### Run Reddit MCP Server (HTTP Server) Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/overview.md Starts the Reddit MCP Server with an HTTP transport, exposing an \`/mcp\` endpoint. This is useful for containerized or web-based deployments. It can optionally be protected with OAuth. ```bash TRANSPORT_TYPE=httpStream PORT=3000 node dist/index.js ``` -------------------------------- ### Example Markdown for Top Reddit Posts Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Shows the markdown format for listing top posts from a subreddit, including title, author, score, comments, date, and link. ```markdown # Top Posts from r/typescript (week) ### 1. Generics in TypeScript explained - Author: u/john_doe - Score: 1,500 (89.0% upvoted) - Comments: 200 - Posted: 2024-06-10 15:30:00 - Link: https://reddit.com/r/typescript/comments/xyz789/... ``` -------------------------------- ### LRU Eviction Example Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/response-cache.md Demonstrates how the ResponseCache evicts the least recently used item when the byte budget is exceeded. Accessing an item does not reorder it until it's explicitly retrieved. ```typescript const cache = new ResponseCache({ maxBytes: 200 }) const url1 = "...hot1" const body1 = "x".repeat(100) // 100 bytes const url2 = "...hot2" const body2 = "x".repeat(100) // 100 bytes const url3 = "...hot3" const body3 = "x".repeat(100) // 100 bytes cache.set(url1, body1, 200) // currentBytes: 100 cache.set(url2, body2, 200) // currentBytes: 200 cache.set(url3, body3, 200) // currentBytes: 300 // Evict url1 (oldest) cache.get(url1) // => undefined (evicted) cache.get(url2) // => { body: body2, status: 200 } (still cached) cache.get(url3) // => { body: body3, status: 200 } (still cached) ``` -------------------------------- ### RedditClient makeRequest Pseudo-code with Caching Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/response-cache.md Illustrates the logic within RedditClient's makeRequest method for handling cache lookups and storage for GET requests. ```typescript async makeRequest(path: string, options?: RequestInit) { const url = `${this.baseUrl}${path}` const method = (options?.method ?? "GET").toUpperCase() const cacheable = this.cache !== undefined && method === "GET" // Cache lookup if (cacheable) { const cached = this.cache!.get(url) if (cached !== undefined) { return Right(new Response(cached.body, { status: cached.status })) } } // Fetch const response = await fetch(url, { ...options, headers }) // Cache storage (only on success) if (cacheable && response.ok) { const text = await response.text() this.cache!.set(url, text, response.status) return Right(new Response(text, { status: response.status })) } return Right(response) } ``` -------------------------------- ### Example: Delete Comment Success Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md This is an example of a success message after a comment has been permanently deleted. It includes a warning that the action cannot be undone. ```markdown # Comment Deleted Successfully The comment t1_def456 has been permanently deleted from Reddit. **Note**: This action cannot be undone. The comment content has been removed and cannot be recovered. ``` -------------------------------- ### Example: Edit Comment Success Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md This is an example of a success message when a comment has been edited. It confirms the edit and notes that an 'edited' marker will appear on the comment. ```markdown # Comment Edited Successfully The comment t1_def456 has been updated with your new content. **Note**: An "edited" marker will appear on your comment to show it has been modified. ``` -------------------------------- ### Production Build and Run Commands Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/INDEX.md Commands for building the project for production and running it in either Stdio or HTTP mode. Configuration for HTTP mode is also shown. ```bash pnpm build npx reddit-mcp-server # Stdio mode (CLI) # or TRANSPORT_TYPE=httpStream PORT=3000 node dist/index.js # HTTP mode ``` -------------------------------- ### Edit Post Example Response Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Example of a successful response after editing a Reddit self-text post. It notes the edit-only capability and the automatic 'edited' marker. ```markdown # Post Edited Successfully The post t3_abc123 has been updated with your new content. **Note**: - Only self (text) posts can be edited - Post titles cannot be edited - Link posts cannot be edited - An "edited" marker will appear on your post ``` -------------------------------- ### Directory Structure Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/overview.md Illustrates the project's directory layout, showing the organization of source files, compiled output, and configuration. ```bash reddit-mcp-server/ ├── src/ │ ├── index.ts # Main MCP server definition and tool setup │ ├── bin.ts # CLI entry point │ ├── types.ts # All TypeScript type definitions │ ├── client/ │ │ ├── reddit-client.ts # Core Reddit API client (singleton) │ │ ├── response-cache.ts # LRU cache for GET responses │ │ └── __tests__/ # Client tests │ ├── tools/ # Tool implementations (modular by category) │ │ ├── post-tools.ts │ │ ├── comment-tools.ts │ │ ├── subreddit-tools.ts │ │ ├── user-tools.ts │ │ ├── search-tools.ts │ │ └── __tests__/ │ └── utils/ │ ├── formatters.ts # Text formatting and analysis helpers │ └── __tests__/ ├── dist/ # Compiled JavaScript (generated by build) ├── package.json # npm metadata, scripts, dependencies ├── tsconfig.json # TypeScript configuration ├── vitest.config.ts # Test configuration └── README.md # User-facing documentation ``` -------------------------------- ### Example Trending Subreddits Response Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Shows the expected markdown format for a list of trending subreddit names. ```markdown # Trending Subreddits 1. r/AskReddit 2. r/funny 3. r/gaming 4. r/news 5. r/movies ``` -------------------------------- ### Configure Reddit MCP Server using .env File for Development Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/configuration.md Sets up environment variables for Reddit MCP Server development by loading configurations from a local .env file. ```bash # Reddit API REDDIT_CLIENT_ID=your_client_id REDDIT_CLIENT_SECRET=your_client_secret REDDIT_USERNAME=your_username REDDIT_PASSWORD=your_password # Configuration REDDIT_AUTH_MODE=auto REDDIT_SAFE_MODE=standard REDDIT_BOT_DISCLOSURE=auto REDDIT_CACHE=on REDDIT_CACHE_MAX_MB=50 # Transport TRANSPORT_TYPE=stdio ``` ```bash set -o allexport source .env set +o allexport npm run dev ``` -------------------------------- ### Get Trending Subreddits Schema Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Defines the input schema for fetching trending subreddits, which requires no parameters. ```typescript z.object({}) ``` -------------------------------- ### get_top_posts Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Get top posts from a subreddit or the Reddit home feed, with options for time filter and limit. ```APIDOC ## get_top_posts ### Description Get top posts from a subreddit or the Reddit home feed. ### Parameters #### Query Parameters - **subreddit** (string) - Optional - Subreddit name without `r/` prefix. Leave empty for home feed - **time_filter** (enum) - Optional, Default: "week" - Values: hour, day, week, month, year, all - Time period for top posts - **limit** (number) - Optional, Default: 10 - Min: 1, Max: 100 - Number of posts to retrieve ### Response Formatted markdown listing posts with title, author, score, comments, date, and link. ### Example ```markdown # Top Posts from r/typescript (week) ### 1. Generics in TypeScript explained - Author: u/john_doe - Score: 1,500 (89.0% upvoted) - Comments: 200 - Posted: 2024-06-10 15:30:00 - Link: https://reddit.com/r/typescript/comments/xyz789/... ``` ### Error conditions: - Subreddit not found (HTTP 404) - Network failure - No posts found (empty result) ``` -------------------------------- ### Get Subreddit Information Schema Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Defines the input schema for retrieving subreddit information, requiring the subreddit name. ```typescript z.object({ subreddit_name: z.string().describe("The subreddit name (without r/ prefix)") }) ``` -------------------------------- ### Development Commands Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/README.md Common commands for managing project dependencies, building, running, testing, and formatting the code. ```bash pnpm install # Install dependencies pnpm build # Build TypeScript pnpm dev # Build and run MCP inspector pnpm test # Run tests pnpm lint # Lint code pnpm format # Format code ``` -------------------------------- ### get_reddit_post Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Get detailed information about a specific Reddit post with engagement analysis. Requires subreddit and post ID. ```APIDOC ## get_reddit_post ### Description Get detailed information about a specific Reddit post with engagement analysis. ### Parameters #### Path Parameters - **subreddit** (string) - Yes - Subreddit name without `r/` prefix - **post_id** (string) - Yes - Post ID without `t3_` prefix ### Response Comprehensive markdown with sections: - Post Details (title, type, author) - Content (body or link) - Stats (score, upvote ratio, comments) - Metadata (created date, flags, flair) - Links (full and short URLs) - Engagement Analysis (qualitative assessment) - Best Time to Engage (posting time recommendation) ### Example ```markdown # Post from r/typescript ## Post Details - Title: How to use generics effectively - Type: self - Author: u/torvalds ## Content This is the full text content of the post... ## Stats - Score: 2,500 - Upvote Ratio: 95.0% - Comments: 250 ## Engagement Analysis - Highly successful post with strong community approval - Generated significant discussion ``` ### Error conditions: - Post not found (HTTP 404) - Network failure - API error ``` -------------------------------- ### Initialize Reddit Client Configuration Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/types.md Sets up the configuration object for initializing the Reddit client. Ensure environment variables for credentials are set, and configure optional features like safe mode, bot disclosure, and caching. ```typescript import { initializeRedditClient } from "./client/reddit-client" const config: RedditClientConfig = { clientId: process.env.REDDIT_CLIENT_ID ?? "", clientSecret: process.env.REDDIT_CLIENT_SECRET ?? "", userAgent: "MyApp/1.0.0 (by /u/myusername)", username: process.env.REDDIT_USERNAME, password: process.env.REDDIT_PASSWORD, authMode: "auto", safeMode: { enabled: true, mode: "standard", writeDelayMs: 2000, duplicateCheck: true, maxRecentHashes: 10, }, botDisclosure: { enabled: true, footer: "\n\n---\n🤖 I am a bot", }, cache: { enabled: true, maxBytes: 50 * 1024 * 1024, }, } const client = initializeRedditClient(config) ``` -------------------------------- ### Run via CLI Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/overview.md Execute the Reddit MCP Server using npx for command-line interaction. This method uses the default stdio transport. ```bash npx reddit-mcp-server ``` -------------------------------- ### Get Saved Content Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/ROADMAP.md Retrieves a list of content that the specified user has saved, with options for filtering by type and limiting results. ```APIDOC ## Get Saved Content ### Description Fetches a list of posts or comments that a user has previously saved. ### Method GET ### Endpoint `/user/{username}/saved` ### Parameters #### Path Parameters - **username** (string) - Required - The username of the user whose saved content to retrieve. #### Query Parameters - **type** (string) - Optional - Filter saved content by type ('user' for comments, 'links' for posts). - **limit** (integer) - Optional - Maximum number of saved items to return. ``` -------------------------------- ### Create FastMCP Server Instance Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/server-initialization.md Instantiates the FastMCP server with essential metadata and system instructions. Optionally includes OAuth authentication middleware if the OAUTH_ENABLED environment variable is set to 'true'. ```typescript const server = new FastMCP({ name: "reddit-mcp-server", version: VERSION, instructions: `A comprehensive Reddit MCP server...`, // Optional OAuth authentication (HTTP transport only) ...(process.env.OAUTH_ENABLED === "true" && { authenticate: (request) => { // ... OAuth validation logic ... }, }), }) ``` -------------------------------- ### Get Post Comments Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/ROADMAP.md Retrieves comments for a specific Reddit post, allowing for sorting and limiting the number of comments returned. ```APIDOC ## Get Post Comments ### Description Fetches comments associated with a specific Reddit post. Supports sorting and limiting the number of comments. ### Method GET ### Endpoint `/r/{subreddit}/comments/{article}` ### Parameters #### Path Parameters - **subreddit** (string) - Required - The subreddit the post belongs to. - **article** (string) - Required - The ID of the post. #### Query Parameters - **sort** (string) - Optional - How to sort comments (e.g., 'best', 'top', 'new'). - **limit** (integer) - Optional - Maximum number of comments to retrieve. ``` -------------------------------- ### Initialize Reddit Client Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/server-initialization.md Initializes the singleton RedditClient instance with all gathered configuration options. ```typescript const client = initializeRedditClient({ clientId: clientId ?? "", clientSecret: clientSecret ?? "", userAgent, username, password, authMode, safeMode: safeModeConfig, botDisclosure: botDisclosureConfig, cache: cacheConfig, }) ``` -------------------------------- ### Format Code Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CLAUDE.md Formats the project code using Prettier. ```bash pnpm format ``` -------------------------------- ### Get Subreddit Information Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/reddit-client.md Fetches metadata and statistics for a specified subreddit. Handles cases where the subreddit is not found or API errors occur. ```typescript const result = await client.getSubredditInfo("typescript") result.fold( (err) => console.error(err.message), (sr) => console.log(`r/${sr.displayName}: ${sr.subscribers.toLocaleString()} subscribers`), ) ``` -------------------------------- ### Initialize RedditClient Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/reddit-client.md Initializes a new Reddit API client with the provided configuration. Ensure you have the necessary credentials and user agent defined. ```typescript import { RedditClient } from "./client/reddit-client" import type { RedditClientConfig } from "./types" const config: RedditClientConfig = { clientId: "your_client_id", clientSecret: "your_client_secret", userAgent: "MyApp/1.0 (by /u/username)", authMode: "auto", } const client = new RedditClient(config) ``` -------------------------------- ### Build Docker Image Locally Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/README.md Build the Docker image from the local source code and run it as a detached container using an environment file. ```bash docker build -t reddit-mcp-server . docker run -d --name reddit-mcp -p 3000:3000 --env-file .env reddit-mcp-server ``` -------------------------------- ### Make Authenticated HTTP Request Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/README.md Example of making an authenticated POST request to the MCP server's HTTP endpoint using curl. ```bash curl -H "Authorization: Bearer $OAUTH_TOKEN" \ -H "Content-Type: application/json" \ -d '{"method":"tools/list","params":{}}' \ http://localhost:3000/mcp ``` -------------------------------- ### Create Post Parameters Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Defines the schema for creating a new Reddit post. Use this to structure the input for the create_post tool. ```typescript z.object({ subreddit: z.string().describe("The subreddit name (without r/ prefix)"), title: z.string().describe("The post title"), content: z.string().describe("The post content (text for self posts, URL for link posts)"), is_self: z.boolean().default(true).describe("Whether this is a self post (text) or link post") }) ``` -------------------------------- ### Get Reddit Post Details Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Retrieves detailed information and engagement analysis for a specific Reddit post. Requires subreddit and post ID. ```typescript z.object({ subreddit: z.string().describe("The subreddit name (without r/ prefix)"), post_id: z.string().describe("The Reddit post ID") }) ``` -------------------------------- ### Get User Information Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/mcp-tools.md Retrieve detailed information about a Reddit user, including their karma breakdown and activity analysis. Requires the username as a parameter. ```typescript z.object({ username: z.string().describe("The Reddit username (without u/ prefix)") }) ``` ```markdown # User Information: u/torvalds ## Profile Overview - Username: u/torvalds - Karma: - Comment Karma: 150,000 - Post Karma: 50,000 - Total Karma: 200,000 - Account Status: Not Gold, Not Employee, ... - Account Created: 2007-01-01 12:34:56 UTC ## Activity Analysis - Long-time Redditor with extensive platform experience - Primarily a commenter, highly engaged in discussions - ... ``` -------------------------------- ### Build Project Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CLAUDE.md Builds the TypeScript project to JavaScript using tsup. ```bash pnpm build ``` -------------------------------- ### Develop and Run Inspector Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CLAUDE.md Builds and runs the MCP inspector in a single command. ```bash pnpm dev ``` -------------------------------- ### Check Code Formatting Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/CLAUDE.md Checks if the project code adheres to formatting standards using Prettier. ```bash pnpm format:check ``` -------------------------------- ### Get User Comments Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/reddit-client.md Fetches comments made by a specific user, with options for sorting, time filter, and limit. Returns either an array of comments or an error. ```typescript async getUserComments( username: string, options?: { sort?: "new" | "hot" | "top" timeFilter?: "hour" | "day" | "week" | "month" | "year" | "all" limit?: number }, ): Promise> ``` ```typescript const result = await client.getUserComments("username", { sort: "top", timeFilter: "month", limit: 50, }) ``` -------------------------------- ### Get User Posts Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/reddit-client.md Fetches posts submitted by a specific user, with options for sorting, time filter, and limit. Returns either an array of posts or an error. ```typescript async getUserPosts( username: string, options?: { sort?: "new" | "hot" | "top" timeFilter?: "hour" | "day" | "week" | "month" | "year" | "all" limit?: number }, ): Promise> ``` ```typescript const result = await client.getUserPosts("torvalds", { sort: "top", timeFilter: "year", limit: 25, }) ``` -------------------------------- ### Get Reddit User Profile Source: https://github.com/jordanburke/reddit-mcp-server/blob/main/_autodocs/reddit-client.md Fetches public profile information for a given Reddit username. Handles cases where the user is not found or API errors occur. ```typescript const result = await client.getUser("spez") result.fold( (err) => console.error("User not found:", err.message), (user) => console.log(`${user.name} has ${user.totalKarma} karma`), ) ```