reddit-mcp-server 1.6.3 → 1.7.1

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
@@ -4,7 +4,7 @@ import { FastMCP } from "fastmcp";
4
4
  import { Left, Option, Right, Try } from "functype";
5
5
  import { z } from "zod";
6
6
  import { XMLParser } from "fast-xml-parser";
7
- //#region src/client/errors.ts
7
+ // src/client/errors.ts
8
8
  /**
9
9
  * Typed error channel for the Reddit client.
10
10
  *
@@ -90,8 +90,7 @@ function classifyRedditError(error, context) {
90
90
  if (isRedditError(error)) return error;
91
91
  return new UnknownError(Option(context).fold(() => error.message, (ctx) => `${ctx}: ${error.message}`), error);
92
92
  }
93
- //#endregion
94
- //#region src/utils/reddit-identifiers.ts
93
+ // src/utils/reddit-identifiers.ts
95
94
  /**
96
95
  * Validation and normalization for Reddit identifiers that get interpolated into API paths.
97
96
  *
@@ -155,8 +154,351 @@ function normalizeFullname(input, defaultKind) {
155
154
  const trimmed = input.trim().toLowerCase();
156
155
  return `${trimmed.startsWith("t1_") ? "t1" : trimmed.startsWith("t3_") ? "t3" : defaultKind}_${normalizeThingId(input)}`;
157
156
  }
158
- //#endregion
159
- //#region src/client/response-cache.ts
157
+ // src/client/reddit-parsers.ts
158
+ function parsePostData(post) {
159
+ return {
160
+ id: post.id,
161
+ title: post.title,
162
+ author: post.author,
163
+ subreddit: post.subreddit,
164
+ selftext: post.selftext,
165
+ url: post.url,
166
+ score: post.score,
167
+ upvoteRatio: post.upvote_ratio,
168
+ numComments: post.num_comments,
169
+ createdUtc: post.created_utc,
170
+ over18: post.over_18,
171
+ spoiler: post.spoiler,
172
+ edited: Boolean(post.edited),
173
+ isSelf: post.is_self,
174
+ linkFlairText: post.link_flair_text ?? void 0,
175
+ permalink: post.permalink
176
+ };
177
+ }
178
+ function parseCommentData(comment, submissionTitle, depth) {
179
+ return {
180
+ id: comment.id,
181
+ author: comment.author,
182
+ body: comment.body ?? "",
183
+ score: comment.score,
184
+ controversiality: comment.controversiality,
185
+ subreddit: comment.subreddit,
186
+ submissionTitle: submissionTitle ?? comment.link_title ?? "",
187
+ createdUtc: comment.created_utc,
188
+ edited: Boolean(comment.edited),
189
+ isSubmitter: comment.is_submitter,
190
+ permalink: comment.permalink,
191
+ ...depth !== void 0 ? { depth } : {},
192
+ parentId: comment.parent_id
193
+ };
194
+ }
195
+ function parseCommentTree(children, submissionTitle, depth = 0) {
196
+ return children.flatMap((item) => {
197
+ if (item.kind !== "t1" || item.data.body === void 0) return [];
198
+ const { replies } = item.data;
199
+ const childComments = replies !== void 0 && typeof replies !== "string" ? parseCommentTree(replies.data.children, submissionTitle, depth + 1) : [];
200
+ return [parseCommentData(item.data, submissionTitle, depth), ...childComments];
201
+ });
202
+ }
203
+ function collectMoreIds(children) {
204
+ return children.flatMap((item) => {
205
+ if (item.kind === "more") {
206
+ const ids = item.data.children;
207
+ return Array.isArray(ids) ? ids.filter((id) => typeof id === "string" && id !== "_") : [];
208
+ }
209
+ const { replies } = item.data;
210
+ return replies !== void 0 && typeof replies !== "string" ? collectMoreIds(replies.data.children) : [];
211
+ });
212
+ }
213
+ function parseSubredditData(data) {
214
+ return {
215
+ displayName: data.display_name,
216
+ title: data.title,
217
+ description: data.description,
218
+ publicDescription: data.public_description,
219
+ subscribers: data.subscribers,
220
+ activeUserCount: data.active_user_count ?? void 0,
221
+ createdUtc: data.created_utc,
222
+ over18: data.over18,
223
+ subredditType: data.subreddit_type,
224
+ url: data.url
225
+ };
226
+ }
227
+ function parseRuleData(rule) {
228
+ return {
229
+ shortName: rule.short_name,
230
+ description: rule.description,
231
+ kind: rule.kind,
232
+ violationReason: rule.violation_reason,
233
+ priority: rule.priority,
234
+ createdUtc: rule.created_utc
235
+ };
236
+ }
237
+ function parseSubredditSearchData(sub) {
238
+ return {
239
+ id: String(sub.id ?? sub.display_name),
240
+ title: `r/${sub.display_name} (${sub.subscribers.toLocaleString("en-US")} subscribers)${sub.title ? ` — ${sub.title}` : ""}`,
241
+ author: "",
242
+ subreddit: sub.display_name,
243
+ selftext: sub.public_description,
244
+ url: `https://reddit.com${sub.url}`,
245
+ score: sub.subscribers,
246
+ upvoteRatio: 1,
247
+ numComments: 0,
248
+ createdUtc: sub.created_utc,
249
+ over18: sub.over18,
250
+ edited: false,
251
+ isSelf: false,
252
+ permalink: sub.url
253
+ };
254
+ }
255
+ function parseUserSearchData(user) {
256
+ const karma = user.total_karma ?? user.link_karma + user.comment_karma;
257
+ return {
258
+ id: user.id,
259
+ title: `u/${user.name} (${karma.toLocaleString("en-US")} karma)`,
260
+ author: user.name,
261
+ subreddit: "",
262
+ url: `https://reddit.com/user/${user.name}`,
263
+ score: karma,
264
+ upvoteRatio: 1,
265
+ numComments: 0,
266
+ createdUtc: user.created_utc,
267
+ over18: false,
268
+ edited: false,
269
+ isSelf: false,
270
+ permalink: `/user/${user.name}`
271
+ };
272
+ }
273
+ // src/client/arctic-shift-client.ts
274
+ /**
275
+ * Keyless read backend over the Arctic Shift archive (https://github.com/ArthurHeitmann/arctic_shift),
276
+ * a free third-party Reddit archive. It is not Reddit's API:
277
+ * - It sorts only by creation date, so there is no hot/top/rising ranking and no home feed.
278
+ * - Scores and comment counts are captured at ingest and lag (often 0 or 1 on recent posts).
279
+ * - Coverage can be incomplete, especially for comments on recent posts.
280
+ * - Keyword search needs a subreddit or author; multireddits (`a+b`) are not supported.
281
+ * Pagination walks backward in time: the `after` cursor is the created_utc of the last item.
282
+ */
283
+ const BASE_URL = "https://arctic-shift.photon-reddit.com/api";
284
+ const MAX_LIMIT = 100;
285
+ const MAX_COMMENT_TREE_LIMIT = 500;
286
+ const ERROR_TEXT_MAX_LENGTH = 200;
287
+ const CURSOR_PATTERN = /^\d{9,10}$/;
288
+ const THROTTLE_RETRY_DELAY_MS = 3e3;
289
+ function clampLimit(limit, max = MAX_LIMIT) {
290
+ return Math.min(Math.max(Math.trunc(limit), 1), max);
291
+ }
292
+ function singleSubreddit(subreddit) {
293
+ const name = normalizeSubreddit(subreddit);
294
+ if (name === "") throw new ValidationError("The Arctic Shift archive has no home feed. Name a subreddit, or set REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET.");
295
+ if (name.includes("+")) throw new ValidationError(`The Arctic Shift archive does not support multireddits ("${name}"). Query one at a time.`);
296
+ return name;
297
+ }
298
+ function isArchiveCursor(after) {
299
+ return CURSOR_PATTERN.test(after);
300
+ }
301
+ const TIME_FILTER_OFFSETS = {
302
+ hour: "1hour",
303
+ day: "1d",
304
+ week: "7d",
305
+ month: "30d",
306
+ year: "365d"
307
+ };
308
+ function cursorParam(after) {
309
+ if (after === void 0) return {};
310
+ if (!isArchiveCursor(after)) throw new ValidationError(`Invalid pagination cursor "${after}". In keyless mode, pass the \`after\` value from a previous keyless call.`);
311
+ return { before: after };
312
+ }
313
+ function pageOf(items, limit) {
314
+ const last = items.at(-1);
315
+ return {
316
+ items,
317
+ source: "arctic",
318
+ ...items.length >= limit && last !== void 0 ? { after: String(last.createdUtc) } : {}
319
+ };
320
+ }
321
+ var ArcticShiftClient = class {
322
+ userAgent;
323
+ cache;
324
+ throttleRetryDelayMs;
325
+ constructor(userAgent, cache, throttleRetryDelayMs = THROTTLE_RETRY_DELAY_MS) {
326
+ this.userAgent = userAgent;
327
+ this.cache = cache;
328
+ this.throttleRetryDelayMs = throttleRetryDelayMs;
329
+ }
330
+ async request(path, params, retried = false) {
331
+ var _this$cache, _this$cache2;
332
+ const url = `${BASE_URL}${path}?${new URLSearchParams(params)}`;
333
+ 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.");
336
+ const json = Try(() => JSON.parse(body)).orElse({
337
+ data: null,
338
+ error: `HTTP ${status}`
339
+ });
340
+ if (status < 200 || status >= 300 || json.error !== void 0 || json.data === null) {
341
+ const detail = (json.error ?? `HTTP ${status}`).slice(0, ERROR_TEXT_MAX_LENGTH);
342
+ if (/timeout|timed out/i.test(detail)) {
343
+ if (!retried) {
344
+ await new Promise((resolve) => setTimeout(resolve, this.throttleRetryDelayMs));
345
+ return this.request(path, params, true);
346
+ }
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.");
348
+ }
349
+ throw status >= 400 ? new HttpError(status, `Arctic Shift error: ${detail}`) : new ApiError(`Arctic Shift error: ${detail}`);
350
+ }
351
+ if (cached === void 0) (_this$cache2 = this.cache) === null || _this$cache2 === void 0 || _this$cache2.set(url, body, status);
352
+ return json.data;
353
+ }
354
+ async fetchBody(url) {
355
+ const response = await fetch(url, { headers: {
356
+ "User-Agent": this.userAgent,
357
+ Accept: "application/json"
358
+ } });
359
+ return {
360
+ status: response.status,
361
+ body: await response.text()
362
+ };
363
+ }
364
+ async listSubredditPosts(subreddit, limit = 25, after) {
365
+ const context = `Failed to list r/${subreddit} from the Arctic Shift archive`;
366
+ return (await Try.async(async () => {
367
+ const size = clampLimit(limit);
368
+ return pageOf((await this.request("/posts/search", {
369
+ subreddit: singleSubreddit(subreddit),
370
+ sort: "desc",
371
+ limit: String(size),
372
+ ...cursorParam(after)
373
+ })).map(parsePostData), size);
374
+ })).toEither((error) => classifyRedditError(error, context));
375
+ }
376
+ async searchPosts(query, options = {}) {
377
+ const { subreddit, limit = 25, after, timeFilter } = options;
378
+ const since = timeFilter !== void 0 ? TIME_FILTER_OFFSETS[timeFilter] : void 0;
379
+ const context = `Failed to search the Arctic Shift archive for: ${query}`;
380
+ return (await Try.async(async () => {
381
+ if (subreddit === void 0) throw new ValidationError("Keyless search needs a subreddit: the Arctic Shift archive cannot search all of Reddit. Pass `subreddit`.");
382
+ const size = clampLimit(limit);
383
+ return pageOf((await this.request("/posts/search", {
384
+ subreddit: singleSubreddit(subreddit),
385
+ query,
386
+ ...since !== void 0 ? { after: since } : {},
387
+ sort: "desc",
388
+ limit: String(size),
389
+ ...cursorParam(after)
390
+ })).map(parsePostData), size);
391
+ })).toEither((error) => classifyRedditError(error, context));
392
+ }
393
+ async searchSubreddits(query, limit = 25) {
394
+ const context = `Failed to search subreddits in the Arctic Shift archive for: ${query}`;
395
+ return (await Try.async(async () => {
396
+ const prefix = query.trim().replace(/^\/?r\//i, "");
397
+ if (!/^[A-Za-z0-9_]+$/.test(prefix)) throw new ValidationError("Keyless subreddit search matches name prefixes only. Use one word of letters, digits, or underscores.");
398
+ return {
399
+ items: (await this.request("/subreddits/search", {
400
+ subreddit_prefix: prefix,
401
+ limit: String(clampLimit(limit))
402
+ })).map(parseSubredditSearchData),
403
+ source: "arctic"
404
+ };
405
+ })).toEither((error) => classifyRedditError(error, context));
406
+ }
407
+ async getPost(postId) {
408
+ const context = `Failed to get post ${postId} from the Arctic Shift archive`;
409
+ return (await Try.async(async () => this.fetchPost(postId))).toEither((error) => classifyRedditError(error, context));
410
+ }
411
+ async fetchPost(postId) {
412
+ const post = (await this.request("/posts/ids", { ids: normalizeThingId(postId) })).at(0);
413
+ if (post === void 0) throw new NotFoundError(`Post ${postId} is not in the Arctic Shift archive`);
414
+ return parsePostData(post);
415
+ }
416
+ async getPostComments(postId, limit = 100) {
417
+ const context = `Failed to get comments for post ${postId} from the Arctic Shift archive`;
418
+ return (await Try.async(async () => {
419
+ const post = await this.fetchPost(postId);
420
+ const tree = await this.request("/comments/tree", {
421
+ link_id: `t3_${post.id}`,
422
+ limit: String(clampLimit(limit, MAX_COMMENT_TREE_LIMIT))
423
+ });
424
+ return {
425
+ post,
426
+ comments: parseCommentTree(tree, post.title),
427
+ moreIds: collectMoreIds(tree)
428
+ };
429
+ })).toEither((error) => classifyRedditError(error, context));
430
+ }
431
+ async getComments(commentIds) {
432
+ const context = "Failed to expand comments from the Arctic Shift archive";
433
+ return (await Try.async(async () => {
434
+ return (await this.request("/comments/ids", { ids: commentIds.map((id) => normalizeThingId(id)).join(",") })).map((comment) => parseCommentData(comment));
435
+ })).toEither((error) => classifyRedditError(error, context));
436
+ }
437
+ async getUser(username) {
438
+ const context = `Failed to get user ${username} from the Arctic Shift archive`;
439
+ return (await Try.async(async () => {
440
+ const user = (await this.request("/users/search", { author: normalizeUsername(username) })).at(0);
441
+ if (user === void 0) throw new NotFoundError(`User ${username} is not in the Arctic Shift archive`);
442
+ const meta = user._meta ?? {};
443
+ const linkKarma = meta.post_karma ?? 0;
444
+ const commentKarma = meta.comment_karma ?? 0;
445
+ const firstSeen = [meta.earliest_post_at, meta.earliest_comment_at].filter((value) => typeof value === "number");
446
+ return {
447
+ name: user.author,
448
+ id: user.id ?? "",
449
+ commentKarma,
450
+ linkKarma,
451
+ totalKarma: meta.total_karma ?? linkKarma + commentKarma,
452
+ isMod: false,
453
+ isGold: false,
454
+ isEmployee: false,
455
+ createdUtc: firstSeen.length > 0 ? Math.min(...firstSeen) : 0,
456
+ profileUrl: `https://reddit.com/user/${user.author}`
457
+ };
458
+ })).toEither((error) => classifyRedditError(error, context));
459
+ }
460
+ async getUserPosts(username, limit = 25, after) {
461
+ const context = `Failed to get posts for user ${username} from the Arctic Shift archive`;
462
+ return (await Try.async(async () => {
463
+ const size = clampLimit(limit);
464
+ return pageOf((await this.request("/posts/search", {
465
+ author: normalizeUsername(username),
466
+ sort: "desc",
467
+ limit: String(size),
468
+ ...cursorParam(after)
469
+ })).map(parsePostData), size);
470
+ })).toEither((error) => classifyRedditError(error, context));
471
+ }
472
+ async getUserComments(username, limit = 25, after) {
473
+ const context = `Failed to get comments for user ${username} from the Arctic Shift archive`;
474
+ return (await Try.async(async () => {
475
+ const size = clampLimit(limit);
476
+ return pageOf((await this.request("/comments/search", {
477
+ author: normalizeUsername(username),
478
+ sort: "desc",
479
+ limit: String(size),
480
+ ...cursorParam(after)
481
+ })).map((comment) => parseCommentData(comment)), size);
482
+ })).toEither((error) => classifyRedditError(error, context));
483
+ }
484
+ async getSubredditInfo(subreddit) {
485
+ const context = `Failed to get r/${subreddit} from the Arctic Shift archive`;
486
+ return (await Try.async(async () => {
487
+ const sub = (await this.request("/subreddits/search", { subreddit: singleSubreddit(subreddit) })).at(0);
488
+ if (sub === void 0) throw new NotFoundError(`r/${subreddit} is not in the Arctic Shift archive`);
489
+ return parseSubredditData(sub);
490
+ })).toEither((error) => classifyRedditError(error, context));
491
+ }
492
+ async getSubredditRules(subreddit) {
493
+ const context = `Failed to get rules for r/${subreddit} from the Arctic Shift archive`;
494
+ return (await Try.async(async () => {
495
+ const entry = (await this.request("/subreddits/rules", { subreddits: singleSubreddit(subreddit) })).at(0);
496
+ if (entry === void 0) throw new NotFoundError(`No rules for r/${subreddit} in the Arctic Shift archive`);
497
+ return entry.rules.map(parseRuleData);
498
+ })).toEither((error) => classifyRedditError(error, context));
499
+ }
500
+ };
501
+ // src/client/response-cache.ts
160
502
  const SECOND = 1e3;
161
503
  var ResponseCache = class {
162
504
  maxBytes;
@@ -216,8 +558,7 @@ var ResponseCache = class {
216
558
  }
217
559
  }
218
560
  };
219
- //#endregion
220
- //#region src/client/rss-client.ts
561
+ // src/client/rss-client.ts
221
562
  function contentText(content) {
222
563
  if (content === void 0) return "";
223
564
  if (typeof content === "string") return content;
@@ -310,8 +651,7 @@ var RssClient = class {
310
651
  })).toEither((error) => classifyRedditError(error, "RSS fetch"));
311
652
  }
312
653
  };
313
- //#endregion
314
- //#region src/client/reddit-client.ts
654
+ // src/client/reddit-client.ts
315
655
  function listingCursor(data) {
316
656
  const after = typeof data.after === "string" ? { after: data.after } : {};
317
657
  const before = typeof data.before === "string" ? { before: data.before } : {};
@@ -320,60 +660,11 @@ function listingCursor(data) {
320
660
  ...before
321
661
  };
322
662
  }
323
- function parsePostData(post) {
663
+ function withIgnoredSortNotice(page, sort) {
664
+ if (sort === void 0 || sort === "new") return page;
324
665
  return {
325
- id: post.id,
326
- title: post.title,
327
- author: post.author,
328
- subreddit: post.subreddit,
329
- selftext: post.selftext,
330
- url: post.url,
331
- score: post.score,
332
- upvoteRatio: post.upvote_ratio,
333
- numComments: post.num_comments,
334
- createdUtc: post.created_utc,
335
- over18: post.over_18,
336
- spoiler: post.spoiler,
337
- edited: Boolean(post.edited),
338
- isSelf: post.is_self,
339
- linkFlairText: post.link_flair_text ?? void 0,
340
- permalink: post.permalink
341
- };
342
- }
343
- function parseSubredditSearchData(sub) {
344
- return {
345
- id: String(sub.id ?? sub.display_name),
346
- title: `r/${sub.display_name} (${sub.subscribers.toLocaleString("en-US")} subscribers)${sub.title ? ` — ${sub.title}` : ""}`,
347
- author: "",
348
- subreddit: sub.display_name,
349
- selftext: sub.public_description,
350
- url: `https://reddit.com${sub.url}`,
351
- score: sub.subscribers,
352
- upvoteRatio: 1,
353
- numComments: 0,
354
- createdUtc: sub.created_utc,
355
- over18: sub.over18,
356
- edited: false,
357
- isSelf: false,
358
- permalink: sub.url
359
- };
360
- }
361
- function parseUserSearchData(user) {
362
- const karma = user.total_karma ?? user.link_karma + user.comment_karma;
363
- return {
364
- id: user.id,
365
- title: `u/${user.name} (${karma.toLocaleString("en-US")} karma)`,
366
- author: user.name,
367
- subreddit: "",
368
- url: `https://reddit.com/user/${user.name}`,
369
- score: karma,
370
- upvoteRatio: 1,
371
- numComments: 0,
372
- createdUtc: user.created_utc,
373
- over18: false,
374
- edited: false,
375
- isSelf: false,
376
- permalink: `/user/${user.name}`
666
+ ...page,
667
+ notice: `Archive results are newest-first; sort="${sort}" was ignored.`
377
668
  };
378
669
  }
379
670
  var RedditClient = class {
@@ -390,7 +681,8 @@ var RedditClient = class {
390
681
  cache;
391
682
  retry;
392
683
  rssClient;
393
- usesRss;
684
+ arctic;
685
+ keyless;
394
686
  accessToken;
395
687
  tokenExpiry = 0;
396
688
  authenticated = false;
@@ -423,8 +715,9 @@ var RedditClient = class {
423
715
  baseDelayMs: 1e3,
424
716
  maxDelayMs: 6e4
425
717
  };
426
- this.usesRss = this.authMode === "anonymous" || this.authMode === "auto" && !this.hasCredentials;
718
+ this.keyless = this.authMode === "anonymous" || this.authMode === "auto" && !this.hasCredentials;
427
719
  this.rssClient = new RssClient(this.userAgent);
720
+ this.arctic = new ArcticShiftClient(this.userAgent, this.cache);
428
721
  }
429
722
  determineBaseUrl() {
430
723
  switch (this.authMode) {
@@ -509,7 +802,7 @@ var RedditClient = class {
509
802
  return true;
510
803
  }
511
804
  validateWriteAccess() {
512
- if (this.usesRss) throw new NotAuthenticatedError("Write operations require OAuth credentials (REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET) in addition to REDDIT_USERNAME and REDDIT_PASSWORD.");
805
+ if (this.keyless) throw new NotAuthenticatedError("Write operations require OAuth credentials (REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET) in addition to REDDIT_USERNAME and REDDIT_PASSWORD.");
513
806
  if (this.username === void 0 || this.password === void 0) throw new NotAuthenticatedError("Write operations require REDDIT_USERNAME and REDDIT_PASSWORD");
514
807
  }
515
808
  async enforceWriteRateLimit() {
@@ -577,10 +870,27 @@ var RedditClient = class {
577
870
  return `${content}${this.botDisclosure.footer}`;
578
871
  }
579
872
  requiresOAuthError(tool) {
580
- return Left(new NotAuthenticatedError(`${tool} requires OAuth credentials (REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET). RSS fallback only supports browse_subreddit and get_top_posts.`));
873
+ return Left(new NotAuthenticatedError(`${tool} requires OAuth credentials (REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET). Keyless mode (RSS feeds and the Arctic Shift archive) cannot provide it.`));
874
+ }
875
+ async keylessListing(subreddit, sort, timeFilter, limit, after) {
876
+ const archivable = subreddit.trim() !== "" && !subreddit.includes("+");
877
+ if (sort === "new" && archivable) return this.arctic.listSubredditPosts(subreddit, limit, after);
878
+ const rss = await this.rssClient.fetchSubredditPosts(subreddit, sort, timeFilter, limit, after);
879
+ const rssProblem = rss.fold((error) => Option(`failed (${error.message})`), (page) => page.items.length === 0 ? Option("returned no posts") : Option.none());
880
+ const cursorFitsArchive = after === void 0 || isArchiveCursor(after);
881
+ if (rssProblem.isEmpty || !archivable || !cursorFitsArchive) return rss;
882
+ return (await this.arctic.listSubredditPosts(subreddit, limit, after)).map((page) => ({
883
+ ...page,
884
+ notice: `The RSS feed ${rssProblem.orElse("failed")}, so these are the newest posts from the Arctic Shift archive, not "${sort}" ranking.`
885
+ }));
886
+ }
887
+ async keylessSearch(query, type, options) {
888
+ if (type === "sr") return this.arctic.searchSubreddits(query, options.limit);
889
+ if (type === "user") return Left(new NotAuthenticatedError("search_reddit type=user requires OAuth credentials. Use get_user_info with an exact username instead."));
890
+ return this.arctic.searchPosts(query, options);
581
891
  }
582
892
  async getUser(username) {
583
- if (this.usesRss) return this.requiresOAuthError("get_user_info");
893
+ if (this.keyless) return this.arctic.getUser(username);
584
894
  const context = `Failed to get user info for ${username}`;
585
895
  return (await Try.async(async () => {
586
896
  const response = (await this.makeRequest(`/user/${normalizeUsername(username)}/about.json`)).orThrow();
@@ -607,29 +917,13 @@ var RedditClient = class {
607
917
  const json = await response.json();
608
918
  return {
609
919
  posts: json.data.children.filter((child) => child.kind === "t3").map((child) => parsePostData(child.data)),
610
- comments: json.data.children.filter((child) => child.kind === "t1").map((child) => {
611
- const comment = child.data;
612
- return {
613
- id: comment.id,
614
- author: comment.author,
615
- body: comment.body ?? "",
616
- score: comment.score,
617
- controversiality: comment.controversiality,
618
- subreddit: comment.subreddit,
619
- submissionTitle: comment.link_title ?? "",
620
- createdUtc: comment.created_utc,
621
- edited: Boolean(comment.edited),
622
- isSubmitter: comment.is_submitter,
623
- permalink: comment.permalink,
624
- parentId: comment.parent_id
625
- };
626
- }),
920
+ comments: json.data.children.filter((child) => child.kind === "t1").map((child) => parseCommentData(child.data)),
627
921
  ...listingCursor(json.data)
628
922
  };
629
923
  })).toEither((error) => classifyRedditError(error, context));
630
924
  }
631
925
  async getMyOverview(options = {}) {
632
- if (this.usesRss) return this.requiresOAuthError("get_my_overview");
926
+ if (this.keyless) return this.requiresOAuthError("get_my_overview");
633
927
  if (this.username === void 0) return Left(new NotAuthenticatedError("Fetching your overview requires REDDIT_USERNAME"));
634
928
  const { limit = 25, after } = options;
635
929
  const params = new URLSearchParams({ limit: limit.toString() });
@@ -637,7 +931,7 @@ var RedditClient = class {
637
931
  return this.getUserContent(`/user/${encodeURIComponent(this.username)}/overview.json?${params}`, "Failed to get your overview");
638
932
  }
639
933
  async getMySaved(options = {}) {
640
- if (this.usesRss) return this.requiresOAuthError("get_my_saved");
934
+ if (this.keyless) return this.requiresOAuthError("get_my_saved");
641
935
  if (this.username === void 0) return Left(new NotAuthenticatedError("Fetching saved content requires REDDIT_USERNAME"));
642
936
  const { limit = 25, after } = options;
643
937
  const params = new URLSearchParams({ limit: limit.toString() });
@@ -645,7 +939,7 @@ var RedditClient = class {
645
939
  return this.getUserContent(`/user/${encodeURIComponent(this.username)}/saved.json?${params}`, "Failed to get saved content");
646
940
  }
647
941
  async getMe() {
648
- if (this.usesRss) return this.requiresOAuthError("get_me");
942
+ if (this.keyless) return this.requiresOAuthError("get_me");
649
943
  if (this.username === void 0) return Left(new NotAuthenticatedError("Fetching your account requires REDDIT_USERNAME"));
650
944
  const context = "Failed to get authenticated user info";
651
945
  return (await Try.async(async () => {
@@ -667,44 +961,25 @@ var RedditClient = class {
667
961
  })).toEither((error) => classifyRedditError(error, context));
668
962
  }
669
963
  async getSubredditInfo(subredditName) {
670
- if (this.usesRss) return this.requiresOAuthError("get_subreddit_info");
964
+ if (this.keyless) return this.arctic.getSubredditInfo(subredditName);
671
965
  const context = `Failed to get subreddit info for ${subredditName}`;
672
966
  return (await Try.async(async () => {
673
967
  const response = (await this.makeRequest(`/r/${normalizeSubreddit(subredditName)}/about.json`)).orThrow();
674
968
  if (!response.ok) throw new HttpError(response.status, `${context}: HTTP ${response.status}`);
675
- const { data } = await response.json();
676
- return {
677
- displayName: data.display_name,
678
- title: data.title,
679
- description: data.description,
680
- publicDescription: data.public_description,
681
- subscribers: data.subscribers,
682
- activeUserCount: data.active_user_count ?? void 0,
683
- createdUtc: data.created_utc,
684
- over18: data.over18,
685
- subredditType: data.subreddit_type,
686
- url: data.url
687
- };
969
+ return parseSubredditData((await response.json()).data);
688
970
  })).toEither((error) => classifyRedditError(error, context));
689
971
  }
690
972
  async getSubredditRules(subreddit) {
691
- if (this.usesRss) return this.requiresOAuthError("get_subreddit_rules");
973
+ if (this.keyless) return this.arctic.getSubredditRules(subreddit);
692
974
  const context = `Failed to get rules for r/${subreddit}`;
693
975
  return (await Try.async(async () => {
694
976
  const response = (await this.makeRequest(`/r/${normalizeSubreddit(subreddit)}/about/rules.json`)).orThrow();
695
977
  if (!response.ok) throw new HttpError(response.status, `${context}: HTTP ${response.status}`);
696
- return (await response.json()).rules.map((rule) => ({
697
- shortName: rule.short_name,
698
- description: rule.description,
699
- kind: rule.kind,
700
- violationReason: rule.violation_reason,
701
- priority: rule.priority,
702
- createdUtc: rule.created_utc
703
- }));
978
+ return (await response.json()).rules.map(parseRuleData);
704
979
  })).toEither((error) => classifyRedditError(error, context));
705
980
  }
706
981
  async getPostFlairs(subreddit) {
707
- if (this.usesRss) return this.requiresOAuthError("get_post_flairs");
982
+ if (this.keyless) return this.requiresOAuthError("get_post_flairs");
708
983
  const context = `Failed to get post flairs for r/${subreddit}`;
709
984
  return (await Try.async(async () => {
710
985
  const response = (await this.makeRequest(`/r/${normalizeSubreddit(subreddit)}/api/link_flair_v2.json`)).orThrow();
@@ -718,7 +993,7 @@ var RedditClient = class {
718
993
  })).toEither((error) => classifyRedditError(error, context));
719
994
  }
720
995
  async getTopPosts(subreddit, timeFilter = "week", limit = 10, after) {
721
- if (this.usesRss) return this.rssClient.fetchSubredditPosts(subreddit, "top", timeFilter, limit, after);
996
+ if (this.keyless) return this.keylessListing(subreddit, "top", timeFilter, limit, after);
722
997
  const params = new URLSearchParams({
723
998
  t: timeFilter,
724
999
  limit: limit.toString()
@@ -746,7 +1021,7 @@ var RedditClient = class {
746
1021
  "controversial"
747
1022
  ];
748
1023
  if (!validSorts.includes(sort)) return Left(new ValidationError(`Invalid sort "${sort}". Valid options are: ${validSorts.join(", ")}`));
749
- if (this.usesRss) return this.rssClient.fetchSubredditPosts(subreddit, sort, timeFilter, limit, after);
1024
+ if (this.keyless) return this.keylessListing(subreddit, sort, timeFilter, limit, after);
750
1025
  const params = new URLSearchParams({ limit: limit.toString() });
751
1026
  if (sort === "top" || sort === "controversial") params.set("t", timeFilter);
752
1027
  if (after !== void 0) params.set("after", after);
@@ -765,7 +1040,7 @@ var RedditClient = class {
765
1040
  })).toEither((error) => classifyRedditError(error, context));
766
1041
  }
767
1042
  async getPost(postId, subreddit) {
768
- if (this.usesRss) return this.requiresOAuthError("get_reddit_post");
1043
+ if (this.keyless) return this.arctic.getPost(postId);
769
1044
  const context = `Failed to get post with ID ${postId}`;
770
1045
  return (await Try.async(async () => {
771
1046
  const id = normalizeThingId(postId);
@@ -779,7 +1054,7 @@ var RedditClient = class {
779
1054
  })).toEither((error) => classifyRedditError(error, context));
780
1055
  }
781
1056
  async getTrendingSubreddits(limit = 5) {
782
- if (this.usesRss) return this.requiresOAuthError("get_trending_subreddits");
1057
+ if (this.keyless) return this.requiresOAuthError("get_trending_subreddits");
783
1058
  const params = new URLSearchParams({ limit: limit.toString() });
784
1059
  const context = `Failed to get trending subreddits`;
785
1060
  return (await Try.async(async () => {
@@ -949,8 +1224,16 @@ var RedditClient = class {
949
1224
  return this.setSaved(thingId, false);
950
1225
  }
951
1226
  async searchReddit(query, options = {}) {
952
- if (this.usesRss) return this.requiresOAuthError("search_reddit");
953
1227
  const { subreddit, sort = "relevance", timeFilter = "all", limit = 25, type = "link", after, before } = options;
1228
+ if (this.keyless) {
1229
+ const page = await this.keylessSearch(query, type, {
1230
+ subreddit,
1231
+ limit,
1232
+ after,
1233
+ timeFilter
1234
+ });
1235
+ return type === "sr" || sort === "relevance" ? page : page.map((p) => withIgnoredSortNotice(p, sort));
1236
+ }
954
1237
  const params = new URLSearchParams({
955
1238
  q: query,
956
1239
  sort,
@@ -979,7 +1262,7 @@ var RedditClient = class {
979
1262
  })).toEither((error) => classifyRedditError(error, context));
980
1263
  }
981
1264
  async getPostComments(postId, subreddit, options = {}) {
982
- if (this.usesRss) return this.requiresOAuthError("get_post_comments");
1265
+ if (this.keyless) return this.arctic.getPostComments(postId, options.limit);
983
1266
  const { sort = "best", limit = 100 } = options;
984
1267
  const params = new URLSearchParams({
985
1268
  sort,
@@ -992,34 +1275,15 @@ var RedditClient = class {
992
1275
  const json = await response.json();
993
1276
  const postData = json[0].data.children[0].data;
994
1277
  const post = parsePostData(postData);
995
- const parseComments = (commentData, depth = 0) => commentData.flatMap((item) => {
996
- if (item.kind !== "t1" || item.data.body === void 0) return [];
997
- const comment = {
998
- id: item.data.id,
999
- author: item.data.author,
1000
- body: item.data.body,
1001
- score: item.data.score,
1002
- controversiality: item.data.controversiality,
1003
- subreddit: item.data.subreddit,
1004
- submissionTitle: post.title,
1005
- createdUtc: item.data.created_utc,
1006
- edited: Boolean(item.data.edited),
1007
- isSubmitter: item.data.is_submitter,
1008
- permalink: item.data.permalink,
1009
- depth,
1010
- parentId: item.data.parent_id
1011
- };
1012
- const { replies } = item.data;
1013
- return [comment, ...replies !== void 0 && typeof replies !== "string" ? parseComments(replies.data.children, depth + 1) : []];
1014
- });
1015
1278
  return {
1016
1279
  post,
1017
- comments: parseComments(json[1].data.children)
1280
+ comments: parseCommentTree(json[1].data.children, post.title),
1281
+ moreIds: collectMoreIds(json[1].data.children)
1018
1282
  };
1019
1283
  })).toEither((error) => classifyRedditError(error, context));
1020
1284
  }
1021
1285
  async getMoreComments(linkId, commentIds) {
1022
- if (this.usesRss) return this.requiresOAuthError("get_more_comments");
1286
+ if (this.keyless) return this.arctic.getComments(commentIds);
1023
1287
  const context = `Failed to expand comments for ${linkId}`;
1024
1288
  return (await Try.async(async () => {
1025
1289
  var _json$json$data4;
@@ -1030,27 +1294,11 @@ var RedditClient = class {
1030
1294
  });
1031
1295
  const response = (await this.makeRequest(`/api/morechildren?${params}`)).orThrow();
1032
1296
  if (!response.ok) throw new HttpError(response.status, `${context}: HTTP ${response.status}`);
1033
- return (((_json$json$data4 = (await response.json()).json.data) === null || _json$json$data4 === void 0 ? void 0 : _json$json$data4.things) ?? []).filter((thing) => thing.kind === "t1" && thing.data.body !== void 0).map((thing) => {
1034
- const comment = thing.data;
1035
- return {
1036
- id: comment.id,
1037
- author: comment.author,
1038
- body: comment.body ?? "",
1039
- score: comment.score,
1040
- controversiality: comment.controversiality,
1041
- subreddit: comment.subreddit,
1042
- submissionTitle: comment.link_title ?? "",
1043
- createdUtc: comment.created_utc,
1044
- edited: Boolean(comment.edited),
1045
- isSubmitter: comment.is_submitter,
1046
- permalink: comment.permalink,
1047
- parentId: comment.parent_id
1048
- };
1049
- });
1297
+ return (((_json$json$data4 = (await response.json()).json.data) === null || _json$json$data4 === void 0 ? void 0 : _json$json$data4.things) ?? []).filter((thing) => thing.kind === "t1" && thing.data.body !== void 0).map((thing) => parseCommentData(thing.data));
1050
1298
  })).toEither((error) => classifyRedditError(error, context));
1051
1299
  }
1052
1300
  async getUserPosts(username, options = {}) {
1053
- if (this.usesRss) return this.requiresOAuthError("get_user_posts");
1301
+ if (this.keyless) return (await this.arctic.getUserPosts(username, options.limit, options.after)).map((p) => withIgnoredSortNotice(p, options.sort));
1054
1302
  const { sort = "new", timeFilter = "all", limit = 25, after } = options;
1055
1303
  const params = new URLSearchParams({
1056
1304
  sort,
@@ -1070,7 +1318,7 @@ var RedditClient = class {
1070
1318
  })).toEither((error) => classifyRedditError(error, context));
1071
1319
  }
1072
1320
  async getUserComments(username, options = {}) {
1073
- if (this.usesRss) return this.requiresOAuthError("get_user_comments");
1321
+ if (this.keyless) return (await this.arctic.getUserComments(username, options.limit, options.after)).map((p) => withIgnoredSortNotice(p, options.sort));
1074
1322
  const { sort = "new", timeFilter = "all", limit = 25, after } = options;
1075
1323
  const params = new URLSearchParams({
1076
1324
  sort,
@@ -1084,22 +1332,7 @@ var RedditClient = class {
1084
1332
  if (!response.ok) throw new HttpError(response.status, `${context}: HTTP ${response.status}`);
1085
1333
  const json = await response.json();
1086
1334
  return {
1087
- items: json.data.children.filter((child) => child.kind === "t1").map((child) => {
1088
- const comment = child.data;
1089
- return {
1090
- id: comment.id,
1091
- author: comment.author,
1092
- body: comment.body ?? "",
1093
- score: comment.score,
1094
- controversiality: comment.controversiality,
1095
- subreddit: comment.subreddit,
1096
- submissionTitle: comment.link_title ?? "",
1097
- createdUtc: comment.created_utc,
1098
- edited: Boolean(comment.edited),
1099
- isSubmitter: comment.is_submitter,
1100
- permalink: comment.permalink
1101
- };
1102
- }),
1335
+ items: json.data.children.filter((child) => child.kind === "t1").map((child) => parseCommentData(child.data)),
1103
1336
  ...listingCursor(json.data)
1104
1337
  };
1105
1338
  })).toEither((error) => classifyRedditError(error, context));
@@ -1114,8 +1347,7 @@ function initializeRedditClient(config) {
1114
1347
  function getRedditClient() {
1115
1348
  return clientHolder.instance;
1116
1349
  }
1117
- //#endregion
1118
- //#region src/utils/formatters.ts
1350
+ // src/utils/formatters.ts
1119
1351
  function formatTimestamp(timestamp) {
1120
1352
  return Try(() => {
1121
1353
  return (/* @__PURE__ */ new Date(timestamp * 1e3)).toISOString().replace("T", " ").replace(/\.\d+Z$/, " UTC");
@@ -1129,7 +1361,8 @@ function analyzeUserActivity(karmaRatio, isMod, accountAgeDays) {
1129
1361
  ].join("\n - ");
1130
1362
  }
1131
1363
  function analyzePostEngagement(score, ratio, numComments) {
1132
- 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 - ");
1364
+ 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"] : []];
1365
+ return insights.length > 0 ? insights.join("\n - ") : "Moderate engagement with no standout signals";
1133
1366
  }
1134
1367
  function analyzeSubredditHealth(subscribers, activeUsers, ageDays) {
1135
1368
  const sizeInsights = subscribers > 1e6 ? ["Major subreddit with massive following"] : subscribers > 1e5 ? ["Well-established community"] : subscribers < 1e3 ? ["Niche community, potential for growth"] : [];
@@ -1279,10 +1512,9 @@ function formatCommentInfo(comment, maxLength = COMMENT_CONTENT_MAX_LENGTH) {
1279
1512
  commentAnalysis: analyzeCommentImpact(comment.score, comment.edited, comment.isSubmitter)
1280
1513
  };
1281
1514
  }
1282
- //#endregion
1283
- //#region src/index.ts
1515
+ // src/index.ts
1284
1516
  dotenv.config({ quiet: true });
1285
- const VERSION = "1.6.3";
1517
+ const VERSION = "1.7.1";
1286
1518
  function validateUserAgent(userAgent, username) {
1287
1519
  if (!/^[\w-]+:[\w-]+:[\d.]+ \(by \/u\/\w+\)$/.test(userAgent)) {
1288
1520
  console.error("[Warning] User-Agent does not follow Reddit's recommended format");
@@ -1333,11 +1565,17 @@ function buildSafeModeConfig(safeMode) {
1333
1565
  function unwrapClient() {
1334
1566
  return getRedditClient().orThrow(/* @__PURE__ */ new Error("Reddit client not initialized"));
1335
1567
  }
1336
- function rssDisclaimer(source) {
1337
- return source === "rss" ? "\n\n> **RSS mode** — scores, comment counts, and upvote ratios are unavailable. Set REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET for full data." : "";
1568
+ const ARCHIVE_DISCLAIMER = "\n\n> **Archive mode** — from the Arctic Shift archive, a free third-party copy of Reddit, not Reddit's API. Scores and comment counts lag and are often 0 or 1 on recent posts, and recent comments may be missing. Set REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET for live data.";
1569
+ function sourceDisclaimer(page) {
1570
+ const notice = Option(page.notice).fold(() => "", (text) => `\n\n> **Note** — ${text}`);
1571
+ if (page.source === "rss") return `${notice}\n\n> **RSS mode** — scores, comment counts, and upvote ratios are unavailable. Set REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET for full data.`;
1572
+ return page.source === "arctic" ? `${notice}${ARCHIVE_DISCLAIMER}` : notice;
1573
+ }
1574
+ function archiveDisclaimer(client) {
1575
+ return client.keyless ? ARCHIVE_DISCLAIMER : "";
1338
1576
  }
1339
1577
  function formatPostSummary(post, index, source) {
1340
- const statsLines = source === "rss" ? [] : [`- Score: ${post.stats.score.toLocaleString()} (${(post.stats.upvoteRatio * 100).toFixed(1)}% upvoted)`, `- Comments: ${post.stats.comments.toLocaleString()}`];
1578
+ const statsLines = source === "rss" || source === "arctic" ? [] : [`- Score: ${post.stats.score.toLocaleString()} (${(post.stats.upvoteRatio * 100).toFixed(1)}% upvoted)`, `- Comments: ${post.stats.comments.toLocaleString()}`];
1341
1579
  return [
1342
1580
  `### ${index + 1}. ${post.title}`,
1343
1581
  `- Author: u/${post.author}`,
@@ -1420,8 +1658,9 @@ async function setupRedditClient() {
1420
1658
  console.error(`[Setup] Authentication mode: ${authMode}`);
1421
1659
  if (authMode === "anonymous") console.error("[Warning] REDDIT_AUTH_MODE=anonymous is deprecated; it is now an alias for auto without credentials.");
1422
1660
  if (authMode === "anonymous" || !hasCredentials) {
1423
- console.error("[Setup] RSS fallback mode — no OAuth credentials detected.");
1424
- console.error("[Setup] Only browse_subreddit and get_top_posts are available (~1 req/min, no engagement metrics).");
1661
+ console.error("[Setup] Keyless mode — no OAuth credentials detected.");
1662
+ console.error("[Setup] Reads come from RSS feeds (ranked listings, until Reddit retires them 2026-11-13)");
1663
+ console.error("[Setup] and the Arctic Shift archive (a free third-party Reddit archive; scores lag).");
1425
1664
  console.error("[Setup] Set REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET for full API access (100 req/min).");
1426
1665
  console.error("[Setup] See: https://www.reddit.com/wiki/api");
1427
1666
  } else {
@@ -1514,6 +1753,7 @@ server.addTool({
1514
1753
  return Promise.resolve(`Reddit MCP Server Status:
1515
1754
  - Server: ✓ Running
1516
1755
  - Reddit Client: ${hasAuth} ${client.fold(() => "Not initialized", () => "Initialized")}
1756
+ - Read Source: ${client.fold(() => "Unknown", (c) => c.keyless ? "Keyless (RSS feeds + Arctic Shift archive; scores lag)" : "Reddit API (OAuth)")}
1517
1757
  - Write Access: ${hasWriteAccess} ${hasWriteAccess === "✓" ? "Available" : "Read-only mode"}
1518
1758
  - Version: ${VERSION}
1519
1759
 
@@ -1522,7 +1762,7 @@ Ready to handle Reddit API requests!`);
1522
1762
  });
1523
1763
  server.addTool({
1524
1764
  name: "get_user_info",
1525
- description: "Get a public profile for any Reddit user: comment/post/total karma, account age and status flags, plus a short activity analysis and engagement tips. Read-only; requires OAuth credentials. Returns profile stats only — use get_user_posts / get_user_comments for their actual content. Use get_me instead for your own authenticated account; do NOT expect private fields here, as only public data is returned.",
1765
+ description: "Get a public profile for any Reddit user: comment/post/total karma, account age and status flags, plus a short activity analysis and engagement tips. Read-only; works without credentials via the Arctic Shift archive (scores lag). Returns profile stats only — use get_user_posts / get_user_comments for their actual content. Use get_me instead for your own authenticated account; do NOT expect private fields here, as only public data is returned.",
1526
1766
  annotations: {
1527
1767
  title: "Get User Info",
1528
1768
  readOnlyHint: true,
@@ -1530,7 +1770,8 @@ server.addTool({
1530
1770
  },
1531
1771
  parameters: z.object({ username: z.string().describe("The target user's Reddit username, without the u/ prefix (e.g. 'spez', not 'u/spez').") }),
1532
1772
  execute: async (args) => {
1533
- return (await unwrapClient().getUser(args.username)).fold((err) => {
1773
+ const client = unwrapClient();
1774
+ return (await client.getUser(args.username)).fold((err) => {
1534
1775
  throw new Error(`Failed to get user info: ${err.message}`);
1535
1776
  }, (user) => {
1536
1777
  const formattedUser = formatUserInfo(user);
@@ -1542,15 +1783,15 @@ server.addTool({
1542
1783
  - Comment Karma: ${formattedUser.karma.commentKarma.toLocaleString()}
1543
1784
  - Post Karma: ${formattedUser.karma.postKarma.toLocaleString()}
1544
1785
  - Total Karma: ${formattedUser.karma.totalKarma.toLocaleString()}
1545
- - Account Status: ${formattedUser.accountStatus.join(", ")}
1546
- - Account Created: ${formattedUser.accountCreated}
1786
+ - Account Status: ${client.keyless ? "Unknown (not in the archive)" : formattedUser.accountStatus.join(", ")}
1787
+ - Account Created: ${client.keyless && user.createdUtc === 0 ? "Unknown (no archived activity)" : formattedUser.accountCreated}
1547
1788
  - Profile URL: ${formattedUser.profileUrl}
1548
1789
 
1549
1790
  ## Activity Analysis
1550
1791
  - ${formattedUser.activityAnalysis.replace(/\n {2}- /g, "\n- ")}
1551
1792
 
1552
1793
  ## Recommendations
1553
- - ${formattedUser.recommendations.replace(/\n {2}- /g, "\n- ")}`;
1794
+ - ${formattedUser.recommendations.replace(/\n {2}- /g, "\n- ")}${client.keyless ? "\n\n> Account Created is estimated from the user's first archived post or comment." : ""}${archiveDisclaimer(client)}`;
1554
1795
  });
1555
1796
  }
1556
1797
  });
@@ -1626,7 +1867,7 @@ server.addTool({
1626
1867
  });
1627
1868
  server.addTool({
1628
1869
  name: "get_user_posts",
1629
- description: "Get posts submitted by a specific user, with sort (new/hot/top) and time filter. Read-only; requires OAuth credentials. 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
+ 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.",
1630
1871
  annotations: {
1631
1872
  title: "Get User Posts",
1632
1873
  readOnlyHint: true,
@@ -1672,13 +1913,13 @@ server.addTool({
1672
1913
  }).join("\n\n");
1673
1914
  return `# Posts by u/${args.username} (${args.sort} - ${args.time_filter})
1674
1915
 
1675
- ${postSummaries}${nextPageHint(page.after)}`;
1916
+ ${postSummaries}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
1676
1917
  });
1677
1918
  }
1678
1919
  });
1679
1920
  server.addTool({
1680
1921
  name: "get_user_comments",
1681
- description: "Get comments made by a specific user, with sort (new/hot/top) and time filter. Read-only; requires OAuth credentials. 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
+ 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.",
1682
1923
  annotations: {
1683
1924
  title: "Get User Comments",
1684
1925
  readOnlyHint: true,
@@ -1727,13 +1968,13 @@ In r/${comment.subreddit} on "${comment.submissionTitle}"
1727
1968
  }).join("\n\n");
1728
1969
  return `# Comments by u/${args.username} (${args.sort} - ${args.time_filter})
1729
1970
 
1730
- ${commentSummaries}${nextPageHint(page.after)}`;
1971
+ ${commentSummaries}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
1731
1972
  });
1732
1973
  }
1733
1974
  });
1734
1975
  server.addTool({
1735
1976
  name: "get_reddit_post",
1736
- 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; requires OAuth credentials. 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
+ 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).",
1737
1978
  annotations: {
1738
1979
  title: "Get Reddit Post",
1739
1980
  readOnlyHint: true,
@@ -1744,7 +1985,8 @@ server.addTool({
1744
1985
  post_id: z.string().describe("Base36 post id — the segment after /comments/ in a permalink like reddit.com/r/<sub>/comments/<post_id>/... (e.g. '1abc23'). With or without a t3_ prefix.")
1745
1986
  }),
1746
1987
  execute: async (args) => {
1747
- return (await unwrapClient().getPost(args.post_id, args.subreddit)).fold((err) => {
1988
+ const client = unwrapClient();
1989
+ return (await client.getPost(args.post_id, args.subreddit)).fold((err) => {
1748
1990
  throw new Error(`Failed to get post: ${err.message}`);
1749
1991
  }, (post) => {
1750
1992
  const formattedPost = formatPostInfo(post);
@@ -1776,13 +2018,13 @@ ${formattedPost.content}
1776
2018
  - ${formattedPost.engagementAnalysis.replace(/\n {2}- /g, "\n- ")}
1777
2019
 
1778
2020
  ## Best Time to Engage
1779
- ${formattedPost.bestTimeToEngage}`;
2021
+ ${formattedPost.bestTimeToEngage}${archiveDisclaimer(client)}`;
1780
2022
  });
1781
2023
  }
1782
2024
  });
1783
2025
  server.addTool({
1784
2026
  name: "get_top_posts",
1785
- description: "Get the top-scoring posts from a subreddit — or from the authenticated home feed if no subreddit is given — within a time window (hour…all). Read-only; works without credentials via RSS fallback (titles and links only, no scores or comment counts). Returns a page of posts plus an `after` cursor. This is a shortcut for the 'top' sort; use browse_subreddit for hot/new/rising/controversial, or search_reddit to find posts by keyword.",
2027
+ description: "Get the top-scoring posts from a subreddit — or from the authenticated home feed if no subreddit is given — within a time window (hour…all). Read-only; works without credentials via RSS (titles and links only, no scores); if RSS fails, it falls back to the Arctic Shift archive's newest posts, which have no ranking. Returns a page of posts plus an `after` cursor. This is a shortcut for the 'top' sort; use browse_subreddit for hot/new/rising/controversial, or search_reddit to find posts by keyword.",
1786
2028
  annotations: {
1787
2029
  title: "Get Top Posts",
1788
2030
  readOnlyHint: true,
@@ -1810,13 +2052,13 @@ server.addTool({
1810
2052
  const postSummaries = posts.map(formatPostInfo).map((post, index) => formatPostSummary(post, index, page.source)).join("\n\n");
1811
2053
  return `# Top Posts from ${Option(args.subreddit).fold(() => "Home Feed", (sr) => `r/${sr}`)} (${args.time_filter})
1812
2054
 
1813
- ${postSummaries}${nextPageHint(page.after)}${rssDisclaimer(page.source)}`;
2055
+ ${postSummaries}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
1814
2056
  });
1815
2057
  }
1816
2058
  });
1817
2059
  server.addTool({
1818
2060
  name: "browse_subreddit",
1819
- description: "Browse a subreddit — or the authenticated home feed when no subreddit is given — by sort order: hot, new, top, rising, or controversial. Read-only; works without credentials via RSS fallback (titles and links only, no scores or comment counts). `time_filter` applies only to the top and controversial sorts. Returns a page of posts plus an `after` cursor. Use get_top_posts as a shortcut for the top sort, or search_reddit to find posts by keyword rather than by feed order.",
2061
+ description: "Browse a subreddit — or the authenticated home feed when no subreddit is given — by sort order: hot, new, top, rising, or controversial. Read-only; works without credentials via RSS (titles and links only, no scores); if RSS fails, it falls back to the Arctic Shift archive's newest posts, which have no ranking. `time_filter` applies only to the top and controversial sorts. Returns a page of posts plus an `after` cursor. Use get_top_posts as a shortcut for the top sort, or search_reddit to find posts by keyword rather than by feed order.",
1820
2062
  annotations: {
1821
2063
  title: "Browse Subreddit",
1822
2064
  readOnlyHint: true,
@@ -1854,13 +2096,13 @@ server.addTool({
1854
2096
  const heading = location === "home feed" ? "Home Feed" : location;
1855
2097
  return `# ${args.sort} posts from ${heading} (${args.sort}${timeSuffix})
1856
2098
 
1857
- ${postSummaries}${nextPageHint(page.after)}${rssDisclaimer(page.source)}`;
2099
+ ${postSummaries}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
1858
2100
  });
1859
2101
  }
1860
2102
  });
1861
2103
  server.addTool({
1862
2104
  name: "get_subreddit_info",
1863
- description: "Get a subreddit's profile: title, description, subscriber and active-user counts, creation date, flags, wiki/link URLs, plus a community analysis and posting tips. Read-only; requires OAuth credentials. Returns metadata about the community itself — use browse_subreddit / get_top_posts for its posts, or get_subreddit_rules for its posting rules. Do NOT use this to find subreddits by topic — use search_reddit with type='sr'.",
2105
+ description: "Get a subreddit's profile: title, description, subscriber and active-user counts, creation date, flags, wiki/link URLs, plus a community analysis and posting tips. Read-only; works without credentials via the Arctic Shift archive (scores lag). Returns metadata about the community itself — use browse_subreddit / get_top_posts for its posts, or get_subreddit_rules for its posting rules. Do NOT use this to find subreddits by topic — use search_reddit with type='sr'.",
1864
2106
  annotations: {
1865
2107
  title: "Get Subreddit Info",
1866
2108
  readOnlyHint: true,
@@ -1868,7 +2110,8 @@ server.addTool({
1868
2110
  },
1869
2111
  parameters: z.object({ subreddit_name: z.string().describe("The subreddit name, without the r/ prefix (e.g. 'askscience').") }),
1870
2112
  execute: async (args) => {
1871
- return (await unwrapClient().getSubredditInfo(args.subreddit_name)).fold((err) => {
2113
+ const client = unwrapClient();
2114
+ return (await client.getSubredditInfo(args.subreddit_name)).fold((err) => {
1872
2115
  throw new Error(`Failed to get subreddit info: ${err.message}`);
1873
2116
  }, (subreddit) => {
1874
2117
  const formattedSubreddit = formatSubredditInfo(subreddit);
@@ -1898,13 +2141,13 @@ ${formattedSubreddit.description.full}
1898
2141
  - ${formattedSubreddit.communityAnalysis.replace(/\n {2}- /g, "\n- ")}
1899
2142
 
1900
2143
  ## Engagement Tips
1901
- - ${formattedSubreddit.engagementTips.replace(/\n {2}- /g, "\n- ")}`;
2144
+ - ${formattedSubreddit.engagementTips.replace(/\n {2}- /g, "\n- ")}${archiveDisclaimer(client)}`;
1902
2145
  });
1903
2146
  }
1904
2147
  });
1905
2148
  server.addTool({
1906
2149
  name: "get_subreddit_rules",
1907
- description: "Get a subreddit's posting rules (each rule's name, what it applies to, and its description). Read-only; requires OAuth credentials. Returns the rules list, or a note when the subreddit lists none. Call this before create_post to check requirements and avoid auto-removal. For available post flairs use get_post_flairs instead.",
2150
+ description: "Get a subreddit's posting rules (each rule's name, what it applies to, and its description). Read-only; works without credentials via the Arctic Shift archive (scores lag). Returns the rules list, or a note when the subreddit lists none. Call this before create_post to check requirements and avoid auto-removal. For available post flairs use get_post_flairs instead.",
1908
2151
  annotations: {
1909
2152
  title: "Get Subreddit Rules",
1910
2153
  readOnlyHint: true,
@@ -1912,7 +2155,8 @@ server.addTool({
1912
2155
  },
1913
2156
  parameters: z.object({ subreddit_name: z.string().describe("The subreddit name, without the r/ prefix (e.g. 'AskReddit').") }),
1914
2157
  execute: async (args) => {
1915
- return (await unwrapClient().getSubredditRules(args.subreddit_name)).fold((err) => {
2158
+ const client = unwrapClient();
2159
+ return (await client.getSubredditRules(args.subreddit_name)).fold((err) => {
1916
2160
  throw new Error(`Failed to get subreddit rules: ${err.message}`);
1917
2161
  }, (rules) => {
1918
2162
  if (rules.length === 0) return `r/${args.subreddit_name} has no listed subreddit-specific rules.`;
@@ -1923,7 +2167,7 @@ server.addTool({
1923
2167
  }).join("\n\n");
1924
2168
  return `# Posting Rules for r/${args.subreddit_name}
1925
2169
 
1926
- ${ruleList}`;
2170
+ ${ruleList}${archiveDisclaimer(client)}`;
1927
2171
  });
1928
2172
  }
1929
2173
  });
@@ -1972,7 +2216,7 @@ ${trendingSubreddits.map((subreddit, index) => `${index + 1}. r/${subreddit}`).j
1972
2216
  });
1973
2217
  server.addTool({
1974
2218
  name: "search_reddit",
1975
- description: "Search Reddit for posts — or subreddits/users via `type` — optionally scoped to one subreddit, with sort and time filters. Read-only; requires OAuth credentials. 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
+ 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.",
1976
2220
  annotations: {
1977
2221
  title: "Search Reddit",
1978
2222
  readOnlyHint: true,
@@ -2035,9 +2279,9 @@ server.addTool({
2035
2279
  const searchLocation = Option(args.subreddit).fold(() => "", (sr) => ` in r/${sr}`);
2036
2280
  return `# Reddit Search Results for: "${args.query}"${searchLocation}
2037
2281
 
2038
- Sorted by: ${args.sort} | Time: ${args.time_filter} | Type: ${args.type}
2282
+ Sorted by: ${page.source !== "arctic" ? args.sort : args.type === "sr" ? "subscribers (archive)" : "newest first (archive)"} | Time: ${args.time_filter} | Type: ${args.type}
2039
2283
 
2040
- ${searchResults}${nextPageHint(page.after)}`;
2284
+ ${searchResults}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
2041
2285
  });
2042
2286
  }
2043
2287
  });
@@ -2256,7 +2500,7 @@ ${args.thing_id} has been removed from your saved items.`);
2256
2500
  });
2257
2501
  server.addTool({
2258
2502
  name: "get_post_comments",
2259
- description: "Get the comment thread for a post (by post id + subreddit), sorted best/top/new/controversial/old/qa. Read-only; requires OAuth credentials. Returns the post header plus threaded comments (author, OP/edited badges, score, body, nesting depth) up to `limit`. Long threads are truncated with 'load more' stubs — expand those with get_more_comments. Use get_reddit_post for just the post body, not the thread.",
2503
+ description: "Get the comment thread for a post (by post id + subreddit), sorted best/top/new/controversial/old/qa. Read-only; works without credentials via the Arctic Shift archive (scores lag). Returns the post header plus threaded comments (author, OP/edited badges, score, body, nesting depth) up to `limit`. Long threads are truncated with 'load more' stubs — expand those with get_more_comments. Use get_reddit_post for just the post body, not the thread.",
2260
2504
  annotations: {
2261
2505
  title: "Get Post Comments",
2262
2506
  readOnlyHint: true,
@@ -2283,18 +2527,18 @@ server.addTool({
2283
2527
  limit: args.limit
2284
2528
  })).fold((err) => {
2285
2529
  throw new Error(`Failed to get comments: ${err.message}`);
2286
- }, ({ post, comments }) => {
2530
+ }, ({ post, comments, moreIds }) => {
2531
+ const statsLine = client.keyless ? "" : `- Score: ${post.score.toLocaleString()} | Comments: ${post.numComments.toLocaleString()}\n`;
2287
2532
  const header = `# Comments for: ${post.title}
2288
2533
 
2289
2534
  **Post by u/${post.author} in r/${post.subreddit}**
2290
- - Score: ${post.score.toLocaleString()} | Comments: ${post.numComments.toLocaleString()}
2291
- - Posted: ${(/* @__PURE__ */ new Date(post.createdUtc * 1e3)).toLocaleString()}
2535
+ ${statsLine}- Posted: ${(/* @__PURE__ */ new Date(post.createdUtc * 1e3)).toLocaleString()}
2292
2536
 
2293
2537
  ---
2294
2538
 
2295
2539
  `;
2296
2540
  if (comments.length === 0) return `${header}No comments found for this post.`;
2297
- return header + comments.map((comment) => {
2541
+ const commentSummaries = comments.map((comment) => {
2298
2542
  const indent = "└─".repeat(Math.min(comment.depth ?? 0, 3));
2299
2543
  const authorBadge = comment.isSubmitter ? " **[OP]**" : "";
2300
2544
  const editedBadge = comment.edited ? " *(edited)*" : "";
@@ -2304,12 +2548,15 @@ ${comment.body}
2304
2548
 
2305
2549
  ---`;
2306
2550
  }).join("\n\n");
2551
+ const moreHint = moreIds.length > 0 ? `\n\n**${moreIds.length} more comments are collapsed.** Expand them with get_more_comments: link_id="t3_${post.id}", comment_ids=${JSON.stringify(moreIds.slice(0, 100))}${moreIds.length > 100 ? " (first 100 shown)" : ""}` : "";
2552
+ const sortNote = client.keyless && args.sort !== "best" ? `\n\n> sort="${args.sort}" is not applied to archive comments.` : "";
2553
+ return header + commentSummaries + moreHint + sortNote + archiveDisclaimer(client);
2307
2554
  });
2308
2555
  }
2309
2556
  });
2310
2557
  server.addTool({
2311
2558
  name: "get_more_comments",
2312
- description: "Expand truncated 'load more comments' stubs in a thread. Read-only; requires OAuth credentials. Pass the post's link id and the comment ids from a 'more' node (surfaced by get_post_comments) to fetch those hidden comments; returns the expanded comments (author, body excerpt, score, link). Call get_post_comments first to obtain the thread and its 'more' node ids — do NOT invent ids.",
2559
+ description: "Expand truncated 'load more comments' stubs in a thread. Read-only; works without credentials via the Arctic Shift archive (scores lag). Pass the post's link id and the comment ids from a 'more' node (surfaced by get_post_comments) to fetch those hidden comments; returns the expanded comments (author, body excerpt, score, link). Call get_post_comments first to obtain the thread and its 'more' node ids — do NOT invent ids.",
2313
2560
  annotations: {
2314
2561
  title: "Get More Comments",
2315
2562
  readOnlyHint: true,
@@ -2320,7 +2567,8 @@ server.addTool({
2320
2567
  comment_ids: z.array(z.string()).min(1).describe("Base36 comment ids to expand, taken from a 'more' node returned by get_post_comments (not arbitrary ids).")
2321
2568
  }),
2322
2569
  execute: async (args) => {
2323
- return (await unwrapClient().getMoreComments(args.link_id, args.comment_ids)).fold((err) => {
2570
+ const client = unwrapClient();
2571
+ return (await client.getMoreComments(args.link_id, args.comment_ids)).fold((err) => {
2324
2572
  throw new Error(`Failed to expand comments: ${err.message}`);
2325
2573
  }, (comments) => {
2326
2574
  if (comments.length === 0) return "No additional comments were returned for those ids.";
@@ -2335,7 +2583,7 @@ server.addTool({
2335
2583
  }).join("\n\n");
2336
2584
  return `# Expanded Comments (${comments.length})
2337
2585
 
2338
- ${commentList}`;
2586
+ ${commentList}${archiveDisclaimer(client)}`;
2339
2587
  });
2340
2588
  }
2341
2589
  });
@@ -2375,7 +2623,6 @@ process.on("SIGTERM", () => {
2375
2623
  process.exit(0);
2376
2624
  });
2377
2625
  main().catch(console.error);
2378
- //#endregion
2379
2626
  export {};
2380
2627
 
2381
2628
  //# sourceMappingURL=index.js.map