reddit-mcp-server 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1363,6 +1363,22 @@ function initializeRedditClient(config) {
1363
1363
  function getRedditClient() {
1364
1364
  return clientHolder.instance;
1365
1365
  }
1366
+ // src/utils/env.ts
1367
+ /**
1368
+ * Read an environment variable, treating an empty or whitespace-only value as unset.
1369
+ *
1370
+ * dotenv turns a `KEY=` line into an empty string, so a copied `.env.example` would
1371
+ * otherwise read as configured: `OAUTH_TOKEN=` locked out every HTTP client, and
1372
+ * `REDDIT_AUTH_MODE=authenticated` with blank credentials started keyless instead of failing.
1373
+ * The value is returned as written; it is not trimmed, so a password may contain spaces.
1374
+ */
1375
+ function readEnv(name, env = process.env) {
1376
+ return Option(env[name]).filter((value) => value.trim() !== "");
1377
+ }
1378
+ /** True when both `REDDIT_USERNAME` and `REDDIT_PASSWORD` are set to non-blank values. */
1379
+ function hasUserCredentials(env = process.env) {
1380
+ return readEnv("REDDIT_USERNAME", env).isSome() && readEnv("REDDIT_PASSWORD", env).isSome();
1381
+ }
1366
1382
  // src/utils/formatters.ts
1367
1383
  function formatTimestamp(timestamp) {
1368
1384
  return Try(() => {
@@ -1532,7 +1548,7 @@ function formatCommentInfo(comment, maxLength = COMMENT_CONTENT_MAX_LENGTH) {
1532
1548
  }
1533
1549
  // src/index.ts
1534
1550
  dotenv.config({ quiet: true });
1535
- const VERSION = "2.0.0";
1551
+ const VERSION = "2.0.2";
1536
1552
  function validateUserAgent(userAgent, username) {
1537
1553
  if (!/^[\w-]+:[\w-]+:[\d.]+ \(by \/u\/\w+\)$/.test(userAgent)) {
1538
1554
  console.error("[Warning] User-Agent does not follow Reddit's recommended format");
@@ -1652,13 +1668,13 @@ function formatUserContent(heading, content) {
1652
1668
  }).join("\n")}\n\n`}${content.posts.length === 0 && content.comments.length === 0 ? "No items found.\n\n" : ""}`.trimEnd() + nextPageHint(content.after);
1653
1669
  }
1654
1670
  async function setupRedditClient() {
1655
- const clientId = process.env.REDDIT_CLIENT_ID;
1656
- const clientSecret = process.env.REDDIT_CLIENT_SECRET;
1657
- const customUserAgent = process.env.REDDIT_USER_AGENT;
1658
- const username = process.env.REDDIT_USERNAME;
1659
- const password = process.env.REDDIT_PASSWORD;
1660
- const authMode = process.env.REDDIT_AUTH_MODE ?? "auto";
1661
- const safeMode = process.env.REDDIT_SAFE_MODE ?? "standard";
1671
+ const clientId = readEnv("REDDIT_CLIENT_ID").orUndefined();
1672
+ const clientSecret = readEnv("REDDIT_CLIENT_SECRET").orUndefined();
1673
+ const customUserAgent = readEnv("REDDIT_USER_AGENT").orUndefined();
1674
+ const username = readEnv("REDDIT_USERNAME").orUndefined();
1675
+ const password = readEnv("REDDIT_PASSWORD").orUndefined();
1676
+ const authMode = readEnv("REDDIT_AUTH_MODE").orElse("auto");
1677
+ const safeMode = readEnv("REDDIT_SAFE_MODE").orElse("standard");
1662
1678
  if (![
1663
1679
  "auto",
1664
1680
  "authenticated",
@@ -1684,18 +1700,18 @@ async function setupRedditClient() {
1684
1700
  const hasCredentials = Boolean(clientId && clientSecret);
1685
1701
  const userAgent = buildUserAgent(customUserAgent, username);
1686
1702
  const safeModeConfig = buildSafeModeConfig(safeMode);
1687
- const botDisclosureMode = process.env.REDDIT_BOT_DISCLOSURE ?? "off";
1703
+ const botDisclosureMode = readEnv("REDDIT_BOT_DISCLOSURE").orElse("off");
1688
1704
  const botDisclosureConfig = {
1689
1705
  enabled: botDisclosureMode === "auto",
1690
- footer: botDisclosureMode === "auto" ? process.env.REDDIT_BOT_FOOTER ?? "\n\n---\n^(🤖 I am a bot | Built with) [^reddit-mcp-server](https://github.com/jordanburke/reddit-mcp-server)" : ""
1706
+ footer: botDisclosureMode === "auto" ? readEnv("REDDIT_BOT_FOOTER").orElse("\n\n---\n^(🤖 I am a bot | Built with) [^reddit-mcp-server](https://github.com/jordanburke/reddit-mcp-server)") : ""
1691
1707
  };
1692
- const cacheEnabled = (process.env.REDDIT_CACHE ?? "on") !== "off";
1693
- const cacheMaxMb = Number(process.env.REDDIT_CACHE_MAX_MB ?? "50");
1708
+ const cacheEnabled = readEnv("REDDIT_CACHE").orElse("on") !== "off";
1709
+ const cacheMaxMb = Number(readEnv("REDDIT_CACHE_MAX_MB").orElse("50"));
1694
1710
  const cacheConfig = {
1695
1711
  enabled: cacheEnabled,
1696
1712
  maxBytes: (Number.isFinite(cacheMaxMb) && cacheMaxMb > 0 ? cacheMaxMb : 50) * 1024 * 1024
1697
1713
  };
1698
- const maxRetriesRaw = Number(process.env.REDDIT_MAX_RETRIES ?? "3");
1714
+ const maxRetriesRaw = Number(readEnv("REDDIT_MAX_RETRIES").orElse("3"));
1699
1715
  const client = initializeRedditClient({
1700
1716
  clientId: clientId ?? "",
1701
1717
  clientSecret: clientSecret ?? "",
@@ -1717,22 +1733,28 @@ async function setupRedditClient() {
1717
1733
  if (authMode === "anonymous") console.error("[Warning] REDDIT_AUTH_MODE=anonymous is deprecated; it is now an alias for auto without credentials.");
1718
1734
  if (authMode === "anonymous" || !hasCredentials) {
1719
1735
  console.error("[Setup] Keyless mode — no OAuth credentials detected.");
1720
- console.error("[Setup] Reads come from RSS feeds (ranked listings, until Reddit retires them 2026-11-13)");
1736
+ console.error("[Setup] Reads come from RSS feeds (ranked listings; Reddit said it would end them 2026-11-13)");
1721
1737
  console.error("[Setup] and the Arctic Shift archive (a free third-party Reddit archive; scores lag).");
1722
- console.error("[Setup] Set REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET for full API access (100 req/min).");
1723
- console.error("[Setup] See: https://www.reddit.com/wiki/api");
1738
+ console.error("[Setup] Existing REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET still give live data (60-100 req/min).");
1739
+ console.error("[Setup] Reddit takes no new API access requests and closes its public API in March 2027.");
1740
+ console.error("[Setup] See: https://github.com/jordanburke/reddit-mcp-server#reddit-is-closing-its-public-api");
1724
1741
  } else {
1725
1742
  console.error("[Setup] Testing Reddit API connection...");
1726
- if (!await client.checkAuthentication()) {
1743
+ if (await client.checkAuthentication()) {
1744
+ console.error("[Setup] ✓ Reddit API connection successful");
1745
+ console.error("[Setup] Using OAuth Reddit API (60-100 req/min)");
1746
+ } else if (authMode === "authenticated") {
1727
1747
  console.error("[Error] ✗ Failed to connect to Reddit API");
1728
1748
  console.error("[Error] Please check your REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET");
1729
1749
  process.exit(1);
1750
+ } else {
1751
+ console.error("[Warning] ✗ Could not authenticate with the Reddit API; starting anyway");
1752
+ console.error("[Warning] Check REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET. Tool calls retry and report the error");
1753
+ console.error("[Warning] Set REDDIT_AUTH_MODE=authenticated to exit on this instead");
1730
1754
  }
1731
- console.error("[Setup] ✓ Reddit API connection successful");
1732
- console.error("[Setup] Using OAuth Reddit API (60-100 req/min)");
1733
1755
  }
1734
1756
  if (username !== void 0 && password !== void 0) {
1735
- console.error(`[Setup] ✓ User authenticated as: ${username}`);
1757
+ console.error(`[Setup] ✓ User credentials set for: ${username}`);
1736
1758
  console.error("[Setup] Write operations enabled (posting, replying, editing, deleting)");
1737
1759
  } else {
1738
1760
  console.error("[Setup] Read-only mode (no user credentials)");
@@ -1749,8 +1771,9 @@ async function setupRedditClient() {
1749
1771
  console.error("[Setup] For Reddit policy compliance, consider REDDIT_BOT_DISCLOSURE=auto");
1750
1772
  }
1751
1773
  }
1752
- const oauthToken = process.env.OAUTH_TOKEN ?? crypto.randomBytes(32).toString("hex");
1753
- if (process.env.OAUTH_ENABLED === "true" && process.env.OAUTH_TOKEN === void 0) console.error(`[Auth] Generated OAuth token: ${oauthToken}`);
1774
+ const configuredOauthToken = readEnv("OAUTH_TOKEN");
1775
+ const oauthToken = configuredOauthToken.orElse(crypto.randomBytes(32).toString("hex"));
1776
+ if (readEnv("OAUTH_ENABLED").orElse("false") === "true" && configuredOauthToken.isNone()) console.error(`[Auth] Generated OAuth token: ${oauthToken}`);
1754
1777
  function authenticateBearer(request) {
1755
1778
  const authHeader = getRequestHeader(request, "authorization");
1756
1779
  if (!(authHeader === null || authHeader === void 0 ? void 0 : authHeader.startsWith("Bearer "))) return Promise.reject(new Response(null, { status: 401 }));
@@ -1759,7 +1782,8 @@ function authenticateBearer(request) {
1759
1782
  if (!crypto.timingSafeEqual(tokenHash, expectedHash)) return Promise.reject(new Response(null, { status: 403 }));
1760
1783
  return Promise.resolve({ authenticated: true });
1761
1784
  }
1762
- const useHttp = process.env.TRANSPORT_TYPE === "httpStream" || process.env.TRANSPORT_TYPE === "http";
1785
+ const transportType = readEnv("TRANSPORT_TYPE").orElse("stdio");
1786
+ const useHttp = transportType === "httpStream" || transportType === "http";
1763
1787
  const server = createServer({
1764
1788
  name: "reddit-mcp-server",
1765
1789
  version: VERSION,
@@ -1786,7 +1810,7 @@ IMPORTANT - Reddit Responsible Builder Policy compliance:
1786
1810
  - All bot-generated content must clearly disclose its automated nature
1787
1811
  - Bots must NOT send private/direct messages without explicit user consent
1788
1812
  For details: https://support.reddithelp.com/hc/en-us/articles/42728983564564-Responsible-Builder-Policy`,
1789
- ...useHttp && process.env.OAUTH_ENABLED === "true" ? { authenticate: authenticateBearer } : {},
1813
+ ...useHttp && readEnv("OAUTH_ENABLED").orElse("false") === "true" ? { authenticate: authenticateBearer } : {},
1790
1814
  enableIntrospection: false,
1791
1815
  enableInfoEndpoint: false,
1792
1816
  enableDashboard: false,
@@ -1804,7 +1828,7 @@ server.addTool({
1804
1828
  execute: () => {
1805
1829
  const client = getRedditClient();
1806
1830
  const hasAuth = client.fold(() => "✗", () => "✓");
1807
- const hasWriteAccess = process.env.REDDIT_USERNAME !== void 0 && process.env.REDDIT_PASSWORD !== void 0 ? "✓" : "✗";
1831
+ const hasWriteAccess = hasUserCredentials() ? "✓" : "✗";
1808
1832
  return Promise.resolve(`Reddit MCP Server Status:
1809
1833
  - Server: ✓ Running
1810
1834
  - Reddit Client: ${hasAuth} ${client.fold(() => "Not initialized", () => "Initialized")}
@@ -2320,7 +2344,7 @@ server.addTool({
2320
2344
  }),
2321
2345
  execute: async (args) => {
2322
2346
  const client = unwrapClient();
2323
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2347
+ if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2324
2348
  return (await client.createPost(args.subreddit, args.title, args.content, args.is_self, args.flair_id, args.flair_text)).fold((err) => toolError(`Failed to create post: ${err.message}`), (post) => {
2325
2349
  const formattedPost = formatPostInfo(post);
2326
2350
  return `# Post Created Successfully
@@ -2351,12 +2375,12 @@ server.addTool({
2351
2375
  }),
2352
2376
  execute: async (args) => {
2353
2377
  const client = unwrapClient();
2354
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2378
+ if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2355
2379
  return (await client.replyToPost(args.post_id, args.content)).fold((err) => toolError(`Failed to reply: ${err.message}`), (comment) => `# Reply Posted Successfully
2356
2380
 
2357
2381
  ## Comment Details
2358
2382
  - Posted to: ${args.post_id}
2359
- - Author: u/${process.env.REDDIT_USERNAME}
2383
+ - Author: u/${readEnv("REDDIT_USERNAME").orElse("")}
2360
2384
  - Comment ID: ${comment.id}
2361
2385
 
2362
2386
  Your reply has been successfully posted.`);
@@ -2375,7 +2399,7 @@ server.addTool({
2375
2399
  parameters: z.object({ thing_id: z.string().describe("The post to delete: a full thing id 't3_<id>' or just the base36 post id '<id>' (the 't3_' prefix is added automatically). Must be a post you authored.") }),
2376
2400
  execute: async (args) => {
2377
2401
  const client = unwrapClient();
2378
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2402
+ if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2379
2403
  return (await client.deletePost(args.thing_id)).fold((err) => toolError(`Failed to delete post: ${err.message}`), () => `# Post Deleted Successfully
2380
2404
 
2381
2405
  The post ${args.thing_id} has been permanently deleted from Reddit.
@@ -2396,7 +2420,7 @@ server.addTool({
2396
2420
  parameters: z.object({ thing_id: z.string().describe("The comment to delete: a full thing id 't1_<id>' or just the base36 comment id '<id>' (the 't1_' prefix is added automatically). Must be a comment you authored.") }),
2397
2421
  execute: async (args) => {
2398
2422
  const client = unwrapClient();
2399
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2423
+ if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2400
2424
  return (await client.deleteComment(args.thing_id)).fold((err) => toolError(`Failed to delete comment: ${err.message}`), () => `# Comment Deleted Successfully
2401
2425
 
2402
2426
  The comment ${args.thing_id} has been permanently deleted from Reddit.
@@ -2420,7 +2444,7 @@ server.addTool({
2420
2444
  }),
2421
2445
  execute: async (args) => {
2422
2446
  const client = unwrapClient();
2423
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2447
+ if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2424
2448
  return (await client.editPost(args.thing_id, args.new_text)).fold((err) => toolError(`Failed to edit post: ${err.message}`), () => `# Post Edited Successfully
2425
2449
 
2426
2450
  The post ${args.thing_id} has been updated with your new content.
@@ -2448,7 +2472,7 @@ server.addTool({
2448
2472
  }),
2449
2473
  execute: async (args) => {
2450
2474
  const client = unwrapClient();
2451
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2475
+ if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2452
2476
  return (await client.editComment(args.thing_id, args.new_text)).fold((err) => toolError(`Failed to edit comment: ${err.message}`), () => `# Comment Edited Successfully
2453
2477
 
2454
2478
  The comment ${args.thing_id} has been updated with your new content.
@@ -2472,7 +2496,7 @@ server.addTool({
2472
2496
  }),
2473
2497
  execute: async (args) => {
2474
2498
  const client = unwrapClient();
2475
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2499
+ if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2476
2500
  return (await client.saveContent(args.thing_id, args.category)).fold((err) => toolError(`Failed to save content: ${err.message}`), () => `# Content Saved Successfully
2477
2501
 
2478
2502
  ${args.thing_id} has been saved to your account. Use get_my_saved to view your saved items.`);
@@ -2491,7 +2515,7 @@ server.addTool({
2491
2515
  parameters: z.object({ thing_id: z.string().describe("The post or comment to unsave: a full thing id 't3_<id>' (post) or 't1_<id>' (comment). A bare id is treated as a post.") }),
2492
2516
  execute: async (args) => {
2493
2517
  const client = unwrapClient();
2494
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2518
+ if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2495
2519
  return (await client.unsaveContent(args.thing_id)).fold((err) => toolError(`Failed to unsave content: ${err.message}`), () => `# Content Unsaved Successfully
2496
2520
 
2497
2521
  ${args.thing_id} has been removed from your saved items.`);
@@ -2584,8 +2608,8 @@ ${commentList}${archiveDisclaimer(client)}`;
2584
2608
  });
2585
2609
  async function main() {
2586
2610
  await setupRedditClient();
2587
- const port = parseInt(process.env.PORT ?? "3000");
2588
- const host = process.env.HOST ?? "127.0.0.1";
2611
+ const port = parseInt(readEnv("PORT").orElse("3000"));
2612
+ const host = readEnv("HOST").orElse("127.0.0.1");
2589
2613
  if (useHttp) {
2590
2614
  console.error(`[Setup] Starting HTTP server on ${host}:${port}`);
2591
2615
  await server.start({