reddit-mcp-server 1.7.0 → 1.7.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/README.md CHANGED
@@ -240,7 +240,7 @@ Without OAuth credentials, reads come from two free sources:
240
240
  | `get_subreddit_info`, `get_subreddit_rules` | Arctic Shift | |
241
241
  | `search_reddit` | Arctic Shift | Posts need `subreddit`; `type=sr` matches name prefixes; no `type=user` |
242
242
 
243
- **Archive caveats:** scores and comment counts lag, and are often 0 or 1 on recent posts. Keyword search on large subreddits is slow, and the archive throttles it; the server retries once. Every archive result ends with a note naming the source.
243
+ **Archive caveats:** scores and comment counts lag, and are often 0 or 1 on recent posts. Keyword search on large subreddits is slow, and the archive throttles it. The server waits up to 10 seconds and retries once. If that fails too, the error says when to retry. Every archive result ends with a note naming the source.
244
244
 
245
245
  **Still needs OAuth:** `get_trending_subreddits`, `get_post_flairs`, `get_me`, `get_my_overview`, `get_my_saved`, and all write tools.
246
246
 
package/dist/bin.js CHANGED
@@ -3,12 +3,12 @@
3
3
  process.env.TRANSPORT_TYPE ??= "stdio";
4
4
  const args = process.argv.slice(2);
5
5
  if (args.includes("--version") || args.includes("-v")) {
6
- console.log("1.7.0");
6
+ console.log("1.7.2");
7
7
  process.exit(0);
8
8
  }
9
9
  if (args.includes("--help") || args.includes("-h")) {
10
10
  console.log(`
11
- Reddit MCP Server v1.7.0
11
+ Reddit MCP Server v1.7.2
12
12
 
13
13
  Usage: reddit-mcp-server [options]
14
14
 
package/dist/index.js CHANGED
@@ -285,7 +285,20 @@ const MAX_LIMIT = 100;
285
285
  const MAX_COMMENT_TREE_LIMIT = 500;
286
286
  const ERROR_TEXT_MAX_LENGTH = 200;
287
287
  const CURSOR_PATTERN = /^\d{9,10}$/;
288
- const THROTTLE_RETRY_DELAY_MS = 3e3;
288
+ const THROTTLE_DELAYS = {
289
+ fallbackMs: 3e3,
290
+ maxWaitMs: 1e4
291
+ };
292
+ function throttleWaitMs(resetSeconds, delays) {
293
+ return resetSeconds.fold(() => delays.fallbackMs, (seconds) => Math.min(seconds * 1e3, delays.maxWaitMs));
294
+ }
295
+ function throttleMessage(status, resetSeconds) {
296
+ if (status !== 429) return "Arctic Shift timed out on this query, which it does under load. Wait a few seconds and retry; keyword searches on large subreddits are slowest.";
297
+ return resetSeconds.fold(() => "Arctic Shift's rate limit was reached. It is a free service; wait a minute and retry.", (seconds) => `Arctic Shift's rate limit was reached. It resets in ${seconds} seconds; retry after that.`);
298
+ }
299
+ function resetSecondsOf(headers) {
300
+ return Option(headers.get("x-ratelimit-reset")).filter((raw) => raw.trim() !== "").map(Number).filter((value) => Number.isFinite(value) && value >= 0);
301
+ }
289
302
  function clampLimit(limit, max = MAX_LIMIT) {
290
303
  return Math.min(Math.max(Math.trunc(limit), 1), max);
291
304
  }
@@ -321,30 +334,32 @@ function pageOf(items, limit) {
321
334
  var ArcticShiftClient = class {
322
335
  userAgent;
323
336
  cache;
324
- throttleRetryDelayMs;
325
- constructor(userAgent, cache, throttleRetryDelayMs = THROTTLE_RETRY_DELAY_MS) {
337
+ throttleDelays;
338
+ constructor(userAgent, cache, throttleDelays = THROTTLE_DELAYS) {
326
339
  this.userAgent = userAgent;
327
340
  this.cache = cache;
328
- this.throttleRetryDelayMs = throttleRetryDelayMs;
341
+ this.throttleDelays = throttleDelays;
329
342
  }
330
343
  async request(path, params, retried = false) {
331
344
  var _this$cache, _this$cache2;
332
345
  const url = `${BASE_URL}${path}?${new URLSearchParams(params)}`;
333
346
  const cached = (_this$cache = this.cache) === null || _this$cache === void 0 ? void 0 : _this$cache.get(url);
334
- const { status, body } = cached ?? await this.fetchBody(url);
335
- if (status === 429) throw new HttpError(429, "Arctic Shift rate limit reached. It is a free service; wait a minute and try again.");
347
+ const { status, body, resetSeconds } = cached !== void 0 ? {
348
+ ...cached,
349
+ resetSeconds: Option.none()
350
+ } : await this.fetchBody(url);
336
351
  const json = Try(() => JSON.parse(body)).orElse({
337
352
  data: null,
338
353
  error: `HTTP ${status}`
339
354
  });
340
355
  if (status < 200 || status >= 300 || json.error !== void 0 || json.data === null) {
341
356
  const detail = (json.error ?? `HTTP ${status}`).slice(0, ERROR_TEXT_MAX_LENGTH);
342
- if (/timeout|timed out/i.test(detail)) {
357
+ if (status === 429 || /timeout|timed out/i.test(detail)) {
343
358
  if (!retried) {
344
- await new Promise((resolve) => setTimeout(resolve, this.throttleRetryDelayMs));
359
+ await new Promise((resolve) => setTimeout(resolve, throttleWaitMs(resetSeconds, this.throttleDelays)));
345
360
  return this.request(path, params, true);
346
361
  }
347
- throw new HttpError(status, "Arctic Shift is throttling or timed out on this query. Wait a few seconds and retry; keyword searches on large subreddits are slowest.");
362
+ throw new HttpError(status, throttleMessage(status, resetSeconds));
348
363
  }
349
364
  throw status >= 400 ? new HttpError(status, `Arctic Shift error: ${detail}`) : new ApiError(`Arctic Shift error: ${detail}`);
350
365
  }
@@ -358,7 +373,8 @@ var ArcticShiftClient = class {
358
373
  } });
359
374
  return {
360
375
  status: response.status,
361
- body: await response.text()
376
+ body: await response.text(),
377
+ resetSeconds: resetSecondsOf(response.headers)
362
378
  };
363
379
  }
364
380
  async listSubredditPosts(subreddit, limit = 25, after) {
@@ -1232,7 +1248,7 @@ var RedditClient = class {
1232
1248
  after,
1233
1249
  timeFilter
1234
1250
  });
1235
- return type === "sr" ? page : page.map((p) => withIgnoredSortNotice(p, sort === "new" ? void 0 : sort));
1251
+ return type === "sr" || sort === "relevance" ? page : page.map((p) => withIgnoredSortNotice(p, sort));
1236
1252
  }
1237
1253
  const params = new URLSearchParams({
1238
1254
  q: query,
@@ -1361,17 +1377,20 @@ function analyzeUserActivity(karmaRatio, isMod, accountAgeDays) {
1361
1377
  ].join("\n - ");
1362
1378
  }
1363
1379
  function analyzePostEngagement(score, ratio, numComments) {
1364
- return [...score > 1e3 && ratio > .95 ? ["Highly successful post with strong community approval"] : score > 100 && ratio > .8 ? ["Well-received post with good engagement"] : ratio < .5 ? ["Controversial post that sparked debate"] : [], ...numComments > 100 ? ["Generated significant discussion"] : numComments > score * .5 ? ["Highly discussable content with active comment section"] : numComments === 0 ? ["Yet to receive community interaction"] : []].join("\n - ");
1380
+ const insights = [...score > 1e3 && ratio > .95 ? ["Highly successful post with strong community approval"] : score > 100 && ratio > .8 ? ["Well-received post with good engagement"] : ratio < .5 ? ["Controversial post that sparked debate"] : [], ...numComments > 100 ? ["Generated significant discussion"] : numComments > score * .5 ? ["Highly discussable content with active comment section"] : numComments === 0 ? ["Yet to receive community interaction"] : []];
1381
+ return insights.length > 0 ? insights.join("\n - ") : "Moderate engagement with no standout signals";
1365
1382
  }
1366
1383
  function analyzeSubredditHealth(subscribers, activeUsers, ageDays) {
1367
1384
  const sizeInsights = subscribers > 1e6 ? ["Major subreddit with massive following"] : subscribers > 1e5 ? ["Well-established community"] : subscribers < 1e3 ? ["Niche community, potential for growth"] : [];
1368
1385
  const activityInsights = activeUsers.map((active) => active / subscribers).fold(() => [], (activityRatio) => activityRatio > .1 ? ["Highly active community with strong engagement"] : activityRatio < .01 ? ["Could benefit from more community engagement initiatives"] : []);
1369
1386
  const ageInsights = ageDays > 1825 ? ["Mature subreddit with established culture"] : ageDays < 90 ? ["New subreddit still forming its community"] : [];
1370
- return [
1387
+ const insights = [
1371
1388
  ...sizeInsights,
1372
1389
  ...activityInsights,
1373
1390
  ...ageInsights
1374
- ].join("\n - ");
1391
+ ];
1392
+ const fallback = activeUsers.isEmpty ? "Mid-sized community with no standout age signals; active-user count unavailable" : "Mid-sized community with no standout activity or age signals";
1393
+ return insights.length > 0 ? insights.join("\n - ") : fallback;
1375
1394
  }
1376
1395
  function getUserRecommendations(karmaRatio, isMod, accountAgeDays) {
1377
1396
  const recommendations = [
@@ -1513,7 +1532,7 @@ function formatCommentInfo(comment, maxLength = COMMENT_CONTENT_MAX_LENGTH) {
1513
1532
  }
1514
1533
  // src/index.ts
1515
1534
  dotenv.config({ quiet: true });
1516
- const VERSION = "1.7.0";
1535
+ const VERSION = "1.7.2";
1517
1536
  function validateUserAgent(userAgent, username) {
1518
1537
  if (!/^[\w-]+:[\w-]+:[\d.]+ \(by \/u\/\w+\)$/.test(userAgent)) {
1519
1538
  console.error("[Warning] User-Agent does not follow Reddit's recommended format");
@@ -1573,16 +1592,47 @@ function sourceDisclaimer(page) {
1573
1592
  function archiveDisclaimer(client) {
1574
1593
  return client.keyless ? ARCHIVE_DISCLAIMER : "";
1575
1594
  }
1595
+ function postStatsLines(score, upvoteRatio, comments, source) {
1596
+ return source === "rss" || source === "arctic" ? [] : [`- Score: ${score.toLocaleString()} (${(upvoteRatio * 100).toFixed(1)}% upvoted)`, `- Comments: ${comments.toLocaleString()}`];
1597
+ }
1576
1598
  function formatPostSummary(post, index, source) {
1577
- const statsLines = source === "rss" || source === "arctic" ? [] : [`- Score: ${post.stats.score.toLocaleString()} (${(post.stats.upvoteRatio * 100).toFixed(1)}% upvoted)`, `- Comments: ${post.stats.comments.toLocaleString()}`];
1578
1599
  return [
1579
1600
  `### ${index + 1}. ${post.title}`,
1580
1601
  `- Author: u/${post.author}`,
1581
- ...statsLines,
1602
+ ...postStatsLines(post.stats.score, post.stats.upvoteRatio, post.stats.comments, source),
1582
1603
  `- Posted: ${post.metadata.posted}`,
1583
1604
  `- Link: ${post.links.shortLink}`
1584
1605
  ].join("\n");
1585
1606
  }
1607
+ const SEARCH_ABOUT_MAX_LENGTH = 200;
1608
+ function formatSearchResult(post, index, type, source) {
1609
+ const flags = [...post.over18 ? ["**NSFW**"] : [], ...post.spoiler === true ? ["**Spoiler**"] : []];
1610
+ const heading = `### ${index + 1}. ${[post.title, ...flags].join(" ")}`;
1611
+ const created = (/* @__PURE__ */ new Date(post.createdUtc * 1e3)).toLocaleString();
1612
+ const link = `- Link: https://reddit.com${post.permalink}`;
1613
+ if (type === "sr") {
1614
+ const about = truncateText((post.selftext ?? "").replace(/\s+/g, " ").trim(), SEARCH_ABOUT_MAX_LENGTH);
1615
+ return [
1616
+ heading,
1617
+ ...about !== "" ? [`- About: ${about}`] : [],
1618
+ `- Created: ${created}`,
1619
+ link
1620
+ ].join("\n");
1621
+ }
1622
+ if (type === "user") return [
1623
+ heading,
1624
+ `- Account created: ${created}`,
1625
+ link
1626
+ ].join("\n");
1627
+ return [
1628
+ heading,
1629
+ `- Subreddit: r/${post.subreddit}`,
1630
+ `- Author: u/${post.author}`,
1631
+ ...postStatsLines(post.score, post.upvoteRatio, post.numComments, source),
1632
+ `- Posted: ${created}`,
1633
+ link
1634
+ ].join("\n");
1635
+ }
1586
1636
  function nextPageHint(after) {
1587
1637
  return Option(after).fold(() => "", (cursor) => `\n\n---\nMore results available — call again with after="${cursor}" for the next page.`);
1588
1638
  }
@@ -1866,7 +1916,7 @@ server.addTool({
1866
1916
  });
1867
1917
  server.addTool({
1868
1918
  name: "get_user_posts",
1869
- description: "Get posts submitted by a specific user, with sort (new/hot/top) and time filter. Read-only; works without credentials via the Arctic Shift archive (scores lag). Returns a page of posts (title, subreddit, score, upvote ratio, comment count, permalink) plus an `after` cursor for paging. Use get_user_comments for their comments, or get_user_info for karma/profile stats. Do NOT use this to search a subreddit — use search_reddit or browse_subreddit.",
1919
+ description: "Get posts submitted by a specific user, with sort (new/hot/top) and time filter. Read-only; works without credentials via the Arctic Shift archive, newest first and without scores or comment counts. Returns a page of posts (title, subreddit, score, upvote ratio, comment count, permalink) plus an `after` cursor for paging. Use get_user_comments for their comments, or get_user_info for karma/profile stats. Do NOT use this to search a subreddit — use search_reddit or browse_subreddit.",
1870
1920
  annotations: {
1871
1921
  title: "Get User Posts",
1872
1922
  readOnlyHint: true,
@@ -1903,12 +1953,13 @@ server.addTool({
1903
1953
  if (posts.length === 0) return `No posts found for u/${args.username} with the specified filters.`;
1904
1954
  const postSummaries = posts.map((post, index) => {
1905
1955
  const flags = [...post.over18 ? ["**NSFW**"] : [], ...post.spoiler === true ? ["**Spoiler**"] : []];
1906
- return `### ${index + 1}. ${post.title} ${flags.join(" ")}
1907
- - Subreddit: r/${post.subreddit}
1908
- - Score: ${post.score.toLocaleString()} (${(post.upvoteRatio * 100).toFixed(1)}% upvoted)
1909
- - Comments: ${post.numComments.toLocaleString()}
1910
- - Posted: ${(/* @__PURE__ */ new Date(post.createdUtc * 1e3)).toLocaleString()}
1911
- - Link: https://reddit.com${post.permalink}`;
1956
+ return [
1957
+ `### ${index + 1}. ${[post.title, ...flags].join(" ")}`,
1958
+ `- Subreddit: r/${post.subreddit}`,
1959
+ ...postStatsLines(post.score, post.upvoteRatio, post.numComments, page.source),
1960
+ `- Posted: ${(/* @__PURE__ */ new Date(post.createdUtc * 1e3)).toLocaleString()}`,
1961
+ `- Link: https://reddit.com${post.permalink}`
1962
+ ].join("\n");
1912
1963
  }).join("\n\n");
1913
1964
  return `# Posts by u/${args.username} (${args.sort} - ${args.time_filter})
1914
1965
 
@@ -1918,7 +1969,7 @@ ${postSummaries}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
1918
1969
  });
1919
1970
  server.addTool({
1920
1971
  name: "get_user_comments",
1921
- description: "Get comments made by a specific user, with sort (new/hot/top) and time filter. Read-only; works without credentials via the Arctic Shift archive (scores lag). Returns a page of comments (subreddit, parent post title, body excerpt, score, permalink) plus an `after` cursor. Use get_user_posts for their submissions, or get_user_info for karma/profile stats. Do NOT use this to read one post's thread — use get_post_comments.",
1972
+ description: "Get comments made by a specific user, with sort (new/hot/top) and time filter. Read-only; works without credentials via the Arctic Shift archive, newest first and without scores. Returns a page of comments (subreddit, parent post title, body excerpt, score, permalink) plus an `after` cursor. Use get_user_posts for their submissions, or get_user_info for karma/profile stats. Do NOT use this to read one post's thread — use get_post_comments.",
1922
1973
  annotations: {
1923
1974
  title: "Get User Comments",
1924
1975
  readOnlyHint: true,
@@ -1961,8 +2012,7 @@ In r/${comment.subreddit} on "${comment.submissionTitle}"
1961
2012
 
1962
2013
  > ${formatted.content}
1963
2014
 
1964
- - Score: ${comment.score.toLocaleString()}
1965
- - Posted: ${(/* @__PURE__ */ new Date(comment.createdUtc * 1e3)).toLocaleString()}
2015
+ ${page.source === "arctic" ? "" : `- Score: ${comment.score.toLocaleString()}\n`}- Posted: ${(/* @__PURE__ */ new Date(comment.createdUtc * 1e3)).toLocaleString()}
1966
2016
  - Link: ${formatted.link}`;
1967
2017
  }).join("\n\n");
1968
2018
  return `# Comments by u/${args.username} (${args.sort} - ${args.time_filter})
@@ -1973,7 +2023,7 @@ ${commentSummaries}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
1973
2023
  });
1974
2024
  server.addTool({
1975
2025
  name: "get_reddit_post",
1976
- description: "Get a single post by subreddit + post id: title, author, self-text or link content, score, upvote ratio, comment count, flair/flags, and an engagement analysis. Read-only; works without credentials via the Arctic Shift archive (scores lag). Returns the post only — use get_post_comments for its comment thread. Do NOT use this to list a subreddit's posts (use browse_subreddit / get_top_posts) or to find posts by keyword (use search_reddit).",
2026
+ description: "Get a single post by subreddit + post id: title, author, self-text or link content, score, upvote ratio, comment count, flair/flags, and an engagement analysis. Read-only; works without credentials via the Arctic Shift archive, which omits the score, upvote ratio, comment count and engagement analysis. Returns the post only — use get_post_comments for its comment thread. Do NOT use this to list a subreddit's posts (use browse_subreddit / get_top_posts) or to find posts by keyword (use search_reddit).",
1977
2027
  annotations: {
1978
2028
  title: "Get Reddit Post",
1979
2029
  readOnlyHint: true,
@@ -2000,9 +2050,9 @@ server.addTool({
2000
2050
  ${formattedPost.content}
2001
2051
 
2002
2052
  ## Stats
2003
- - Score: ${formattedPost.stats.score.toLocaleString()}
2053
+ ${client.keyless ? "- Not shown: the archive's scores and comment counts lag, and are often 0 or 1 on recent posts." : `- Score: ${formattedPost.stats.score.toLocaleString()}
2004
2054
  - Upvote Ratio: ${(formattedPost.stats.upvoteRatio * 100).toFixed(1)}%
2005
- - Comments: ${formattedPost.stats.comments.toLocaleString()}
2055
+ - Comments: ${formattedPost.stats.comments.toLocaleString()}`}
2006
2056
 
2007
2057
  ## Metadata
2008
2058
  - Posted: ${formattedPost.metadata.posted}
@@ -2013,10 +2063,7 @@ ${formattedPost.content}
2013
2063
  - Full Post: ${formattedPost.links.fullPost}
2014
2064
  - Short Link: ${formattedPost.links.shortLink}
2015
2065
 
2016
- ## Engagement Analysis
2017
- - ${formattedPost.engagementAnalysis.replace(/\n {2}- /g, "\n- ")}
2018
-
2019
- ## Best Time to Engage
2066
+ ${client.keyless ? "" : `## Engagement Analysis\n- ${formattedPost.engagementAnalysis.replace(/\n {2}- /g, "\n- ")}\n\n`}## Best Time to Engage
2020
2067
  ${formattedPost.bestTimeToEngage}${archiveDisclaimer(client)}`;
2021
2068
  });
2022
2069
  }
@@ -2215,7 +2262,7 @@ ${trendingSubreddits.map((subreddit, index) => `${index + 1}. r/${subreddit}`).j
2215
2262
  });
2216
2263
  server.addTool({
2217
2264
  name: "search_reddit",
2218
- description: "Search Reddit for posts — or subreddits/users via `type` — optionally scoped to one subreddit, with sort and time filters. Read-only. Without credentials it uses the Arctic Shift archive, which needs `subreddit` for post search, matches subreddit names by prefix, and cannot search users. Returns a page of results (title, subreddit, author, score, comments, link) plus an `after` cursor for paging. Use this to find content by keyword; use browse_subreddit / get_top_posts to list a known subreddit's feed instead.",
2265
+ description: "Search Reddit for posts — or subreddits/users via `type` — optionally scoped to one subreddit, with sort and time filters. Read-only. Without credentials it uses the Arctic Shift archive, which needs `subreddit` for post search, matches subreddit names by prefix, cannot search users, and omits scores and comment counts. Returns a page of results (title, subreddit, author, score, comments, link) plus an `after` cursor for paging. Use this to find content by keyword; use browse_subreddit / get_top_posts to list a known subreddit's feed instead.",
2219
2266
  annotations: {
2220
2267
  title: "Search Reddit",
2221
2268
  readOnlyHint: true,
@@ -2265,20 +2312,11 @@ server.addTool({
2265
2312
  const searchLocation = Option(args.subreddit).fold(() => "", (sr) => ` in r/${sr}`);
2266
2313
  return `No results found for "${args.query}"${searchLocation}.`;
2267
2314
  }
2268
- const searchResults = posts.map((post, index) => {
2269
- const flags = [...post.over18 ? ["**NSFW**"] : [], ...post.spoiler === true ? ["**Spoiler**"] : []];
2270
- return `### ${index + 1}. ${post.title} ${flags.join(" ")}
2271
- - Subreddit: r/${post.subreddit}
2272
- - Author: u/${post.author}
2273
- - Score: ${post.score.toLocaleString()} (${(post.upvoteRatio * 100).toFixed(1)}% upvoted)
2274
- - Comments: ${post.numComments.toLocaleString()}
2275
- - Posted: ${(/* @__PURE__ */ new Date(post.createdUtc * 1e3)).toLocaleString()}
2276
- - Link: https://reddit.com${post.permalink}`;
2277
- }).join("\n\n");
2315
+ const searchResults = posts.map((post, index) => formatSearchResult(post, index, args.type, page.source)).join("\n\n");
2278
2316
  const searchLocation = Option(args.subreddit).fold(() => "", (sr) => ` in r/${sr}`);
2279
2317
  return `# Reddit Search Results for: "${args.query}"${searchLocation}
2280
2318
 
2281
- Sorted by: ${args.sort} | Time: ${args.time_filter} | Type: ${args.type}
2319
+ Sorted by: ${page.source !== "arctic" ? args.sort : args.type === "sr" ? "subscribers (archive)" : "newest first (archive)"} | Time: ${args.time_filter} | Type: ${args.type}
2282
2320
 
2283
2321
  ${searchResults}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
2284
2322
  });