reddit-mcp-server 1.7.1 → 2.0.0

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
@@ -1,7 +1,7 @@
1
1
  import crypto from "crypto";
2
2
  import dotenv from "dotenv";
3
- import { FastMCP } from "fastmcp";
4
3
  import { Left, Option, Right, Try } from "functype";
4
+ import { createServer, getRequestHeader } from "somamcp/node";
5
5
  import { z } from "zod";
6
6
  import { XMLParser } from "fast-xml-parser";
7
7
  // src/client/errors.ts
@@ -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) {
@@ -1368,11 +1384,13 @@ function analyzeSubredditHealth(subscribers, activeUsers, ageDays) {
1368
1384
  const sizeInsights = subscribers > 1e6 ? ["Major subreddit with massive following"] : subscribers > 1e5 ? ["Well-established community"] : subscribers < 1e3 ? ["Niche community, potential for growth"] : [];
1369
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"] : []);
1370
1386
  const ageInsights = ageDays > 1825 ? ["Mature subreddit with established culture"] : ageDays < 90 ? ["New subreddit still forming its community"] : [];
1371
- return [
1387
+ const insights = [
1372
1388
  ...sizeInsights,
1373
1389
  ...activityInsights,
1374
1390
  ...ageInsights
1375
- ].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;
1376
1394
  }
1377
1395
  function getUserRecommendations(karmaRatio, isMod, accountAgeDays) {
1378
1396
  const recommendations = [
@@ -1514,7 +1532,7 @@ function formatCommentInfo(comment, maxLength = COMMENT_CONTENT_MAX_LENGTH) {
1514
1532
  }
1515
1533
  // src/index.ts
1516
1534
  dotenv.config({ quiet: true });
1517
- const VERSION = "1.7.1";
1535
+ const VERSION = "2.0.0";
1518
1536
  function validateUserAgent(userAgent, username) {
1519
1537
  if (!/^[\w-]+:[\w-]+:[\d.]+ \(by \/u\/\w+\)$/.test(userAgent)) {
1520
1538
  console.error("[Warning] User-Agent does not follow Reddit's recommended format");
@@ -1562,6 +1580,15 @@ function buildSafeModeConfig(safeMode) {
1562
1580
  };
1563
1581
  }
1564
1582
  }
1583
+ function toolError(text) {
1584
+ return {
1585
+ content: [{
1586
+ text,
1587
+ type: "text"
1588
+ }],
1589
+ isError: true
1590
+ };
1591
+ }
1565
1592
  function unwrapClient() {
1566
1593
  return getRedditClient().orThrow(/* @__PURE__ */ new Error("Reddit client not initialized"));
1567
1594
  }
@@ -1574,16 +1601,47 @@ function sourceDisclaimer(page) {
1574
1601
  function archiveDisclaimer(client) {
1575
1602
  return client.keyless ? ARCHIVE_DISCLAIMER : "";
1576
1603
  }
1604
+ function postStatsLines(score, upvoteRatio, comments, source) {
1605
+ return source === "rss" || source === "arctic" ? [] : [`- Score: ${score.toLocaleString()} (${(upvoteRatio * 100).toFixed(1)}% upvoted)`, `- Comments: ${comments.toLocaleString()}`];
1606
+ }
1577
1607
  function formatPostSummary(post, index, source) {
1578
- const statsLines = source === "rss" || source === "arctic" ? [] : [`- Score: ${post.stats.score.toLocaleString()} (${(post.stats.upvoteRatio * 100).toFixed(1)}% upvoted)`, `- Comments: ${post.stats.comments.toLocaleString()}`];
1579
1608
  return [
1580
1609
  `### ${index + 1}. ${post.title}`,
1581
1610
  `- Author: u/${post.author}`,
1582
- ...statsLines,
1611
+ ...postStatsLines(post.stats.score, post.stats.upvoteRatio, post.stats.comments, source),
1583
1612
  `- Posted: ${post.metadata.posted}`,
1584
1613
  `- Link: ${post.links.shortLink}`
1585
1614
  ].join("\n");
1586
1615
  }
1616
+ const SEARCH_ABOUT_MAX_LENGTH = 200;
1617
+ function formatSearchResult(post, index, type, source) {
1618
+ const flags = [...post.over18 ? ["**NSFW**"] : [], ...post.spoiler === true ? ["**Spoiler**"] : []];
1619
+ const heading = `### ${index + 1}. ${[post.title, ...flags].join(" ")}`;
1620
+ const created = (/* @__PURE__ */ new Date(post.createdUtc * 1e3)).toLocaleString();
1621
+ const link = `- Link: https://reddit.com${post.permalink}`;
1622
+ if (type === "sr") {
1623
+ const about = truncateText((post.selftext ?? "").replace(/\s+/g, " ").trim(), SEARCH_ABOUT_MAX_LENGTH);
1624
+ return [
1625
+ heading,
1626
+ ...about !== "" ? [`- About: ${about}`] : [],
1627
+ `- Created: ${created}`,
1628
+ link
1629
+ ].join("\n");
1630
+ }
1631
+ if (type === "user") return [
1632
+ heading,
1633
+ `- Account created: ${created}`,
1634
+ link
1635
+ ].join("\n");
1636
+ return [
1637
+ heading,
1638
+ `- Subreddit: r/${post.subreddit}`,
1639
+ `- Author: u/${post.author}`,
1640
+ ...postStatsLines(post.score, post.upvoteRatio, post.numComments, source),
1641
+ `- Posted: ${created}`,
1642
+ link
1643
+ ].join("\n");
1644
+ }
1587
1645
  function nextPageHint(after) {
1588
1646
  return Option(after).fold(() => "", (cursor) => `\n\n---\nMore results available — call again with after="${cursor}" for the next page.`);
1589
1647
  }
@@ -1693,7 +1751,16 @@ async function setupRedditClient() {
1693
1751
  }
1694
1752
  const oauthToken = process.env.OAUTH_TOKEN ?? crypto.randomBytes(32).toString("hex");
1695
1753
  if (process.env.OAUTH_ENABLED === "true" && process.env.OAUTH_TOKEN === void 0) console.error(`[Auth] Generated OAuth token: ${oauthToken}`);
1696
- const server = new FastMCP({
1754
+ function authenticateBearer(request) {
1755
+ const authHeader = getRequestHeader(request, "authorization");
1756
+ if (!(authHeader === null || authHeader === void 0 ? void 0 : authHeader.startsWith("Bearer "))) return Promise.reject(new Response(null, { status: 401 }));
1757
+ const tokenHash = crypto.createHash("sha256").update(Buffer.from(authHeader.slice(7))).digest();
1758
+ const expectedHash = crypto.createHash("sha256").update(Buffer.from(oauthToken)).digest();
1759
+ if (!crypto.timingSafeEqual(tokenHash, expectedHash)) return Promise.reject(new Response(null, { status: 403 }));
1760
+ return Promise.resolve({ authenticated: true });
1761
+ }
1762
+ const useHttp = process.env.TRANSPORT_TYPE === "httpStream" || process.env.TRANSPORT_TYPE === "http";
1763
+ const server = createServer({
1697
1764
  name: "reddit-mcp-server",
1698
1765
  version: VERSION,
1699
1766
  instructions: `A comprehensive Reddit MCP server that provides tools for interacting with Reddit API.
@@ -1719,23 +1786,11 @@ IMPORTANT - Reddit Responsible Builder Policy compliance:
1719
1786
  - All bot-generated content must clearly disclose its automated nature
1720
1787
  - Bots must NOT send private/direct messages without explicit user consent
1721
1788
  For details: https://support.reddithelp.com/hc/en-us/articles/42728983564564-Responsible-Builder-Policy`,
1722
- ...process.env.OAUTH_ENABLED === "true" && { authenticate: (request) => {
1723
- const authHeader = request.headers.authorization;
1724
- if (!(authHeader === null || authHeader === void 0 ? void 0 : authHeader.startsWith("Bearer "))) throw new Response(null, {
1725
- status: 401,
1726
- statusText: "Missing or invalid Authorization header"
1727
- });
1728
- const token = authHeader.slice(7);
1729
- const tokenBuffer = Buffer.from(token);
1730
- const expectedBuffer = Buffer.from(oauthToken);
1731
- const tokenHash = crypto.createHash("sha256").update(tokenBuffer).digest();
1732
- const expectedHash = crypto.createHash("sha256").update(expectedBuffer).digest();
1733
- if (!crypto.timingSafeEqual(tokenHash, expectedHash)) throw new Response(null, {
1734
- status: 403,
1735
- statusText: "Invalid token"
1736
- });
1737
- return Promise.resolve({ authenticated: true });
1738
- } }
1789
+ ...useHttp && process.env.OAUTH_ENABLED === "true" ? { authenticate: authenticateBearer } : {},
1790
+ enableIntrospection: false,
1791
+ enableInfoEndpoint: false,
1792
+ enableDashboard: false,
1793
+ streamKeepalive: { enabled: useHttp }
1739
1794
  });
1740
1795
  server.addTool({
1741
1796
  name: "test_reddit_mcp_server",
@@ -1771,9 +1826,7 @@ server.addTool({
1771
1826
  parameters: z.object({ username: z.string().describe("The target user's Reddit username, without the u/ prefix (e.g. 'spez', not 'u/spez').") }),
1772
1827
  execute: async (args) => {
1773
1828
  const client = unwrapClient();
1774
- return (await client.getUser(args.username)).fold((err) => {
1775
- throw new Error(`Failed to get user info: ${err.message}`);
1776
- }, (user) => {
1829
+ return (await client.getUser(args.username)).fold((err) => toolError(`Failed to get user info: ${err.message}`), (user) => {
1777
1830
  const formattedUser = formatUserInfo(user);
1778
1831
  return `# User Information: u/${formattedUser.username}
1779
1832
 
@@ -1805,9 +1858,7 @@ server.addTool({
1805
1858
  },
1806
1859
  parameters: z.object({}),
1807
1860
  execute: async () => {
1808
- return (await unwrapClient().getMe()).fold((err) => {
1809
- throw new Error(`Failed to get authenticated user: ${err.message}`);
1810
- }, (user) => {
1861
+ return (await unwrapClient().getMe()).fold((err) => toolError(`Failed to get authenticated user: ${err.message}`), (user) => {
1811
1862
  const formattedUser = formatUserInfo(user);
1812
1863
  return `# Your Account: u/${formattedUser.username}
1813
1864
 
@@ -1839,9 +1890,7 @@ server.addTool({
1839
1890
  return (await unwrapClient().getMyOverview({
1840
1891
  limit: args.limit,
1841
1892
  after: args.after
1842
- })).fold((err) => {
1843
- throw new Error(`Failed to get your overview: ${err.message}`);
1844
- }, (content) => formatUserContent("Your Overview", content));
1893
+ })).fold((err) => toolError(`Failed to get your overview: ${err.message}`), (content) => formatUserContent("Your Overview", content));
1845
1894
  }
1846
1895
  });
1847
1896
  server.addTool({
@@ -1860,14 +1909,12 @@ server.addTool({
1860
1909
  return (await unwrapClient().getMySaved({
1861
1910
  limit: args.limit,
1862
1911
  after: args.after
1863
- })).fold((err) => {
1864
- throw new Error(`Failed to get saved content: ${err.message}`);
1865
- }, (content) => formatUserContent("Your Saved Content", content));
1912
+ })).fold((err) => toolError(`Failed to get saved content: ${err.message}`), (content) => formatUserContent("Your Saved Content", content));
1866
1913
  }
1867
1914
  });
1868
1915
  server.addTool({
1869
1916
  name: "get_user_posts",
1870
- 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.",
1917
+ 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.",
1871
1918
  annotations: {
1872
1919
  title: "Get User Posts",
1873
1920
  readOnlyHint: true,
@@ -1897,19 +1944,18 @@ server.addTool({
1897
1944
  timeFilter: args.time_filter,
1898
1945
  limit: args.limit,
1899
1946
  after: args.after
1900
- })).fold((err) => {
1901
- throw new Error(`Failed to get user posts: ${err.message}`);
1902
- }, (page) => {
1947
+ })).fold((err) => toolError(`Failed to get user posts: ${err.message}`), (page) => {
1903
1948
  const posts = page.items;
1904
1949
  if (posts.length === 0) return `No posts found for u/${args.username} with the specified filters.`;
1905
1950
  const postSummaries = posts.map((post, index) => {
1906
1951
  const flags = [...post.over18 ? ["**NSFW**"] : [], ...post.spoiler === true ? ["**Spoiler**"] : []];
1907
- return `### ${index + 1}. ${post.title} ${flags.join(" ")}
1908
- - Subreddit: r/${post.subreddit}
1909
- - Score: ${post.score.toLocaleString()} (${(post.upvoteRatio * 100).toFixed(1)}% upvoted)
1910
- - Comments: ${post.numComments.toLocaleString()}
1911
- - Posted: ${(/* @__PURE__ */ new Date(post.createdUtc * 1e3)).toLocaleString()}
1912
- - Link: https://reddit.com${post.permalink}`;
1952
+ return [
1953
+ `### ${index + 1}. ${[post.title, ...flags].join(" ")}`,
1954
+ `- Subreddit: r/${post.subreddit}`,
1955
+ ...postStatsLines(post.score, post.upvoteRatio, post.numComments, page.source),
1956
+ `- Posted: ${(/* @__PURE__ */ new Date(post.createdUtc * 1e3)).toLocaleString()}`,
1957
+ `- Link: https://reddit.com${post.permalink}`
1958
+ ].join("\n");
1913
1959
  }).join("\n\n");
1914
1960
  return `# Posts by u/${args.username} (${args.sort} - ${args.time_filter})
1915
1961
 
@@ -1919,7 +1965,7 @@ ${postSummaries}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
1919
1965
  });
1920
1966
  server.addTool({
1921
1967
  name: "get_user_comments",
1922
- 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.",
1968
+ 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.",
1923
1969
  annotations: {
1924
1970
  title: "Get User Comments",
1925
1971
  readOnlyHint: true,
@@ -1949,9 +1995,7 @@ server.addTool({
1949
1995
  timeFilter: args.time_filter,
1950
1996
  limit: args.limit,
1951
1997
  after: args.after
1952
- })).fold((err) => {
1953
- throw new Error(`Failed to get user comments: ${err.message}`);
1954
- }, (page) => {
1998
+ })).fold((err) => toolError(`Failed to get user comments: ${err.message}`), (page) => {
1955
1999
  const comments = page.items;
1956
2000
  if (comments.length === 0) return `No comments found for u/${args.username} with the specified filters.`;
1957
2001
  const commentSummaries = comments.map((comment, index) => {
@@ -1962,8 +2006,7 @@ In r/${comment.subreddit} on "${comment.submissionTitle}"
1962
2006
 
1963
2007
  > ${formatted.content}
1964
2008
 
1965
- - Score: ${comment.score.toLocaleString()}
1966
- - Posted: ${(/* @__PURE__ */ new Date(comment.createdUtc * 1e3)).toLocaleString()}
2009
+ ${page.source === "arctic" ? "" : `- Score: ${comment.score.toLocaleString()}\n`}- Posted: ${(/* @__PURE__ */ new Date(comment.createdUtc * 1e3)).toLocaleString()}
1967
2010
  - Link: ${formatted.link}`;
1968
2011
  }).join("\n\n");
1969
2012
  return `# Comments by u/${args.username} (${args.sort} - ${args.time_filter})
@@ -1974,7 +2017,7 @@ ${commentSummaries}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
1974
2017
  });
1975
2018
  server.addTool({
1976
2019
  name: "get_reddit_post",
1977
- 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).",
2020
+ 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).",
1978
2021
  annotations: {
1979
2022
  title: "Get Reddit Post",
1980
2023
  readOnlyHint: true,
@@ -1986,9 +2029,7 @@ server.addTool({
1986
2029
  }),
1987
2030
  execute: async (args) => {
1988
2031
  const client = unwrapClient();
1989
- return (await client.getPost(args.post_id, args.subreddit)).fold((err) => {
1990
- throw new Error(`Failed to get post: ${err.message}`);
1991
- }, (post) => {
2032
+ return (await client.getPost(args.post_id, args.subreddit)).fold((err) => toolError(`Failed to get post: ${err.message}`), (post) => {
1992
2033
  const formattedPost = formatPostInfo(post);
1993
2034
  return `# Post from r/${formattedPost.subreddit}
1994
2035
 
@@ -2001,9 +2042,9 @@ server.addTool({
2001
2042
  ${formattedPost.content}
2002
2043
 
2003
2044
  ## Stats
2004
- - Score: ${formattedPost.stats.score.toLocaleString()}
2045
+ ${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()}
2005
2046
  - Upvote Ratio: ${(formattedPost.stats.upvoteRatio * 100).toFixed(1)}%
2006
- - Comments: ${formattedPost.stats.comments.toLocaleString()}
2047
+ - Comments: ${formattedPost.stats.comments.toLocaleString()}`}
2007
2048
 
2008
2049
  ## Metadata
2009
2050
  - Posted: ${formattedPost.metadata.posted}
@@ -2014,10 +2055,7 @@ ${formattedPost.content}
2014
2055
  - Full Post: ${formattedPost.links.fullPost}
2015
2056
  - Short Link: ${formattedPost.links.shortLink}
2016
2057
 
2017
- ## Engagement Analysis
2018
- - ${formattedPost.engagementAnalysis.replace(/\n {2}- /g, "\n- ")}
2019
-
2020
- ## Best Time to Engage
2058
+ ${client.keyless ? "" : `## Engagement Analysis\n- ${formattedPost.engagementAnalysis.replace(/\n {2}- /g, "\n- ")}\n\n`}## Best Time to Engage
2021
2059
  ${formattedPost.bestTimeToEngage}${archiveDisclaimer(client)}`;
2022
2060
  });
2023
2061
  }
@@ -2044,9 +2082,7 @@ server.addTool({
2044
2082
  after: z.string().optional().describe("Forward pagination cursor: the `after` value from a previous call. Omit for the first page.")
2045
2083
  }),
2046
2084
  execute: async (args) => {
2047
- return (await unwrapClient().getTopPosts(args.subreddit ?? "", args.time_filter, args.limit, args.after)).fold((err) => {
2048
- throw new Error(`Failed to get top posts: ${err.message}`);
2049
- }, (page) => {
2085
+ return (await unwrapClient().getTopPosts(args.subreddit ?? "", args.time_filter, args.limit, args.after)).fold((err) => toolError(`Failed to get top posts: ${err.message}`), (page) => {
2050
2086
  const posts = page.items;
2051
2087
  if (posts.length === 0) return `No posts found in ${Option(args.subreddit).fold(() => "home feed", (sr) => `r/${sr}`)} for the specified time period.`;
2052
2088
  const postSummaries = posts.map(formatPostInfo).map((post, index) => formatPostSummary(post, index, page.source)).join("\n\n");
@@ -2085,9 +2121,7 @@ server.addTool({
2085
2121
  after: z.string().optional().describe("Forward pagination cursor: the `after` value from a previous call. Omit for the first page.")
2086
2122
  }),
2087
2123
  execute: async (args) => {
2088
- return (await unwrapClient().browseSubreddit(args.subreddit ?? "", args.sort, args.time_filter, args.limit, args.after)).fold((err) => {
2089
- throw new Error(`Failed to browse subreddit: ${err.message}`);
2090
- }, (page) => {
2124
+ return (await unwrapClient().browseSubreddit(args.subreddit ?? "", args.sort, args.time_filter, args.limit, args.after)).fold((err) => toolError(`Failed to browse subreddit: ${err.message}`), (page) => {
2091
2125
  const posts = page.items;
2092
2126
  const location = Option(args.subreddit).fold(() => "home feed", (sr) => `r/${sr}`);
2093
2127
  if (posts.length === 0) return `No posts found in ${location}.`;
@@ -2111,9 +2145,7 @@ server.addTool({
2111
2145
  parameters: z.object({ subreddit_name: z.string().describe("The subreddit name, without the r/ prefix (e.g. 'askscience').") }),
2112
2146
  execute: async (args) => {
2113
2147
  const client = unwrapClient();
2114
- return (await client.getSubredditInfo(args.subreddit_name)).fold((err) => {
2115
- throw new Error(`Failed to get subreddit info: ${err.message}`);
2116
- }, (subreddit) => {
2148
+ return (await client.getSubredditInfo(args.subreddit_name)).fold((err) => toolError(`Failed to get subreddit info: ${err.message}`), (subreddit) => {
2117
2149
  const formattedSubreddit = formatSubredditInfo(subreddit);
2118
2150
  return `# Subreddit Information: r/${formattedSubreddit.name}
2119
2151
 
@@ -2156,9 +2188,7 @@ server.addTool({
2156
2188
  parameters: z.object({ subreddit_name: z.string().describe("The subreddit name, without the r/ prefix (e.g. 'AskReddit').") }),
2157
2189
  execute: async (args) => {
2158
2190
  const client = unwrapClient();
2159
- return (await client.getSubredditRules(args.subreddit_name)).fold((err) => {
2160
- throw new Error(`Failed to get subreddit rules: ${err.message}`);
2161
- }, (rules) => {
2191
+ return (await client.getSubredditRules(args.subreddit_name)).fold((err) => toolError(`Failed to get subreddit rules: ${err.message}`), (rules) => {
2162
2192
  if (rules.length === 0) return `r/${args.subreddit_name} has no listed subreddit-specific rules.`;
2163
2193
  const ruleList = rules.map((rule, index) => {
2164
2194
  const applies = rule.kind === "all" ? "posts & comments" : `${rule.kind}s`;
@@ -2181,9 +2211,7 @@ server.addTool({
2181
2211
  },
2182
2212
  parameters: z.object({ subreddit_name: z.string().describe("The subreddit name, without the r/ prefix (e.g. 'gadgets').") }),
2183
2213
  execute: async (args) => {
2184
- return (await unwrapClient().getPostFlairs(args.subreddit_name)).fold((err) => {
2185
- throw new Error(`Failed to get post flairs: ${err.message}`);
2186
- }, (flairs) => {
2214
+ return (await unwrapClient().getPostFlairs(args.subreddit_name)).fold((err) => toolError(`Failed to get post flairs: ${err.message}`), (flairs) => {
2187
2215
  if (flairs.length === 0) return `r/${args.subreddit_name} has no selectable link flairs (or none are visible to this account).`;
2188
2216
  const flairList = flairs.map((flair) => {
2189
2217
  const editable = flair.textEditable === true ? " _(text editable)_" : "";
@@ -2207,16 +2235,14 @@ server.addTool({
2207
2235
  },
2208
2236
  parameters: z.object({}),
2209
2237
  execute: async () => {
2210
- return (await unwrapClient().getTrendingSubreddits()).fold((err) => {
2211
- throw new Error(`Failed to get trending subreddits: ${err.message}`);
2212
- }, (trendingSubreddits) => `# Trending Subreddits
2238
+ return (await unwrapClient().getTrendingSubreddits()).fold((err) => toolError(`Failed to get trending subreddits: ${err.message}`), (trendingSubreddits) => `# Trending Subreddits
2213
2239
 
2214
2240
  ${trendingSubreddits.map((subreddit, index) => `${index + 1}. r/${subreddit}`).join("\n")}`);
2215
2241
  }
2216
2242
  });
2217
2243
  server.addTool({
2218
2244
  name: "search_reddit",
2219
- 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.",
2245
+ 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.",
2220
2246
  annotations: {
2221
2247
  title: "Search Reddit",
2222
2248
  readOnlyHint: true,
@@ -2250,7 +2276,7 @@ server.addTool({
2250
2276
  }),
2251
2277
  execute: async (args) => {
2252
2278
  const client = unwrapClient();
2253
- if (args.query.trim() === "") throw new Error("Search query cannot be empty");
2279
+ if (args.query.trim() === "") return toolError("Search query cannot be empty");
2254
2280
  return (await client.searchReddit(args.query, {
2255
2281
  subreddit: args.subreddit,
2256
2282
  sort: args.sort,
@@ -2258,24 +2284,13 @@ server.addTool({
2258
2284
  limit: args.limit,
2259
2285
  type: args.type,
2260
2286
  after: args.after
2261
- })).fold((err) => {
2262
- throw new Error(`Failed to search: ${err.message}`);
2263
- }, (page) => {
2287
+ })).fold((err) => toolError(`Failed to search: ${err.message}`), (page) => {
2264
2288
  const posts = page.items;
2265
2289
  if (posts.length === 0) {
2266
2290
  const searchLocation = Option(args.subreddit).fold(() => "", (sr) => ` in r/${sr}`);
2267
2291
  return `No results found for "${args.query}"${searchLocation}.`;
2268
2292
  }
2269
- const searchResults = posts.map((post, index) => {
2270
- const flags = [...post.over18 ? ["**NSFW**"] : [], ...post.spoiler === true ? ["**Spoiler**"] : []];
2271
- return `### ${index + 1}. ${post.title} ${flags.join(" ")}
2272
- - Subreddit: r/${post.subreddit}
2273
- - Author: u/${post.author}
2274
- - Score: ${post.score.toLocaleString()} (${(post.upvoteRatio * 100).toFixed(1)}% upvoted)
2275
- - Comments: ${post.numComments.toLocaleString()}
2276
- - Posted: ${(/* @__PURE__ */ new Date(post.createdUtc * 1e3)).toLocaleString()}
2277
- - Link: https://reddit.com${post.permalink}`;
2278
- }).join("\n\n");
2293
+ const searchResults = posts.map((post, index) => formatSearchResult(post, index, args.type, page.source)).join("\n\n");
2279
2294
  const searchLocation = Option(args.subreddit).fold(() => "", (sr) => ` in r/${sr}`);
2280
2295
  return `# Reddit Search Results for: "${args.query}"${searchLocation}
2281
2296
 
@@ -2305,10 +2320,8 @@ server.addTool({
2305
2320
  }),
2306
2321
  execute: async (args) => {
2307
2322
  const client = unwrapClient();
2308
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) throw new Error("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2309
- return (await client.createPost(args.subreddit, args.title, args.content, args.is_self, args.flair_id, args.flair_text)).fold((err) => {
2310
- throw new Error(`Failed to create post: ${err.message}`);
2311
- }, (post) => {
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.");
2324
+ 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) => {
2312
2325
  const formattedPost = formatPostInfo(post);
2313
2326
  return `# Post Created Successfully
2314
2327
 
@@ -2338,10 +2351,8 @@ server.addTool({
2338
2351
  }),
2339
2352
  execute: async (args) => {
2340
2353
  const client = unwrapClient();
2341
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) throw new Error("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2342
- return (await client.replyToPost(args.post_id, args.content)).fold((err) => {
2343
- throw new Error(`Failed to reply: ${err.message}`);
2344
- }, (comment) => `# Reply Posted Successfully
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.");
2355
+ return (await client.replyToPost(args.post_id, args.content)).fold((err) => toolError(`Failed to reply: ${err.message}`), (comment) => `# Reply Posted Successfully
2345
2356
 
2346
2357
  ## Comment Details
2347
2358
  - Posted to: ${args.post_id}
@@ -2364,10 +2375,8 @@ server.addTool({
2364
2375
  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.") }),
2365
2376
  execute: async (args) => {
2366
2377
  const client = unwrapClient();
2367
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) throw new Error("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2368
- return (await client.deletePost(args.thing_id)).fold((err) => {
2369
- throw new Error(`Failed to delete post: ${err.message}`);
2370
- }, () => `# Post Deleted Successfully
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.");
2379
+ return (await client.deletePost(args.thing_id)).fold((err) => toolError(`Failed to delete post: ${err.message}`), () => `# Post Deleted Successfully
2371
2380
 
2372
2381
  The post ${args.thing_id} has been permanently deleted from Reddit.
2373
2382
 
@@ -2387,10 +2396,8 @@ server.addTool({
2387
2396
  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.") }),
2388
2397
  execute: async (args) => {
2389
2398
  const client = unwrapClient();
2390
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) throw new Error("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2391
- return (await client.deleteComment(args.thing_id)).fold((err) => {
2392
- throw new Error(`Failed to delete comment: ${err.message}`);
2393
- }, () => `# Comment Deleted Successfully
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.");
2400
+ return (await client.deleteComment(args.thing_id)).fold((err) => toolError(`Failed to delete comment: ${err.message}`), () => `# Comment Deleted Successfully
2394
2401
 
2395
2402
  The comment ${args.thing_id} has been permanently deleted from Reddit.
2396
2403
 
@@ -2413,10 +2420,8 @@ server.addTool({
2413
2420
  }),
2414
2421
  execute: async (args) => {
2415
2422
  const client = unwrapClient();
2416
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) throw new Error("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2417
- return (await client.editPost(args.thing_id, args.new_text)).fold((err) => {
2418
- throw new Error(`Failed to edit post: ${err.message}`);
2419
- }, () => `# Post Edited Successfully
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.");
2424
+ return (await client.editPost(args.thing_id, args.new_text)).fold((err) => toolError(`Failed to edit post: ${err.message}`), () => `# Post Edited Successfully
2420
2425
 
2421
2426
  The post ${args.thing_id} has been updated with your new content.
2422
2427
 
@@ -2443,10 +2448,8 @@ server.addTool({
2443
2448
  }),
2444
2449
  execute: async (args) => {
2445
2450
  const client = unwrapClient();
2446
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) throw new Error("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2447
- return (await client.editComment(args.thing_id, args.new_text)).fold((err) => {
2448
- throw new Error(`Failed to edit comment: ${err.message}`);
2449
- }, () => `# Comment Edited Successfully
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.");
2452
+ return (await client.editComment(args.thing_id, args.new_text)).fold((err) => toolError(`Failed to edit comment: ${err.message}`), () => `# Comment Edited Successfully
2450
2453
 
2451
2454
  The comment ${args.thing_id} has been updated with your new content.
2452
2455
 
@@ -2469,10 +2472,8 @@ server.addTool({
2469
2472
  }),
2470
2473
  execute: async (args) => {
2471
2474
  const client = unwrapClient();
2472
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) throw new Error("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2473
- return (await client.saveContent(args.thing_id, args.category)).fold((err) => {
2474
- throw new Error(`Failed to save content: ${err.message}`);
2475
- }, () => `# Content Saved Successfully
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.");
2476
+ return (await client.saveContent(args.thing_id, args.category)).fold((err) => toolError(`Failed to save content: ${err.message}`), () => `# Content Saved Successfully
2476
2477
 
2477
2478
  ${args.thing_id} has been saved to your account. Use get_my_saved to view your saved items.`);
2478
2479
  }
@@ -2490,10 +2491,8 @@ server.addTool({
2490
2491
  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.") }),
2491
2492
  execute: async (args) => {
2492
2493
  const client = unwrapClient();
2493
- if (process.env.REDDIT_USERNAME === void 0 || process.env.REDDIT_PASSWORD === void 0) throw new Error("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
2494
- return (await client.unsaveContent(args.thing_id)).fold((err) => {
2495
- throw new Error(`Failed to unsave content: ${err.message}`);
2496
- }, () => `# Content Unsaved Successfully
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.");
2495
+ return (await client.unsaveContent(args.thing_id)).fold((err) => toolError(`Failed to unsave content: ${err.message}`), () => `# Content Unsaved Successfully
2497
2496
 
2498
2497
  ${args.thing_id} has been removed from your saved items.`);
2499
2498
  }
@@ -2521,13 +2520,11 @@ server.addTool({
2521
2520
  }),
2522
2521
  execute: async (args) => {
2523
2522
  const client = unwrapClient();
2524
- if (args.post_id === "" || args.subreddit === "") throw new Error("post_id and subreddit are required");
2523
+ if (args.post_id === "" || args.subreddit === "") return toolError("post_id and subreddit are required");
2525
2524
  return (await client.getPostComments(args.post_id, args.subreddit, {
2526
2525
  sort: args.sort,
2527
2526
  limit: args.limit
2528
- })).fold((err) => {
2529
- throw new Error(`Failed to get comments: ${err.message}`);
2530
- }, ({ post, comments, moreIds }) => {
2527
+ })).fold((err) => toolError(`Failed to get comments: ${err.message}`), ({ post, comments, moreIds }) => {
2531
2528
  const statsLine = client.keyless ? "" : `- Score: ${post.score.toLocaleString()} | Comments: ${post.numComments.toLocaleString()}\n`;
2532
2529
  const header = `# Comments for: ${post.title}
2533
2530
 
@@ -2568,9 +2565,7 @@ server.addTool({
2568
2565
  }),
2569
2566
  execute: async (args) => {
2570
2567
  const client = unwrapClient();
2571
- return (await client.getMoreComments(args.link_id, args.comment_ids)).fold((err) => {
2572
- throw new Error(`Failed to expand comments: ${err.message}`);
2573
- }, (comments) => {
2568
+ return (await client.getMoreComments(args.link_id, args.comment_ids)).fold((err) => toolError(`Failed to expand comments: ${err.message}`), (comments) => {
2574
2569
  if (comments.length === 0) return "No additional comments were returned for those ids.";
2575
2570
  const commentList = comments.map((comment, index) => {
2576
2571
  const formatted = formatCommentInfo(comment, 300);
@@ -2589,7 +2584,6 @@ ${commentList}${archiveDisclaimer(client)}`;
2589
2584
  });
2590
2585
  async function main() {
2591
2586
  await setupRedditClient();
2592
- const useHttp = process.env.TRANSPORT_TYPE === "httpStream" || process.env.TRANSPORT_TYPE === "http";
2593
2587
  const port = parseInt(process.env.PORT ?? "3000");
2594
2588
  const host = process.env.HOST ?? "127.0.0.1";
2595
2589
  if (useHttp) {
@@ -2599,11 +2593,11 @@ async function main() {
2599
2593
  httpStream: {
2600
2594
  port,
2601
2595
  host,
2602
- endpoint: "/mcp"
2596
+ endpoint: "/mcp",
2597
+ cors: true
2603
2598
  }
2604
2599
  });
2605
2600
  console.error(`[Setup] HTTP server ready at http://${host}:${port}/mcp`);
2606
- console.error(`[Setup] SSE endpoint available at http://${host}:${port}/sse`);
2607
2601
  } else {
2608
2602
  console.error("[Setup] Starting in stdio mode");
2609
2603
  if (process.stdin.isTTY) {