reddit-mcp-server 1.6.2 → 1.7.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/README.md +26 -16
- package/dist/bin.js +8 -4
- package/dist/bin.js.map +1 -1
- package/dist/index.js +516 -227
- package/dist/index.js.map +1 -1
- package/package.json +12 -12
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
159
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
324
|
-
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) {
|
|
663
|
+
function withIgnoredSortNotice(page, sort) {
|
|
664
|
+
if (sort === void 0 || sort === "new") return page;
|
|
344
665
|
return {
|
|
345
|
-
|
|
346
|
-
|
|
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
|
-
|
|
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.
|
|
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.
|
|
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
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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.
|
|
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(
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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" ? page : page.map((p) => withIgnoredSortNotice(p, sort === "new" ? void 0 : 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.
|
|
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:
|
|
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.
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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");
|
|
@@ -1161,6 +1393,14 @@ function getSubredditEngagementTips(subreddit) {
|
|
|
1161
1393
|
const allTips = [...sizeTips, ...activityTips];
|
|
1162
1394
|
return allTips.length > 0 ? allTips.join("\n - ") : "Regular engagement recommended to maintain community presence";
|
|
1163
1395
|
}
|
|
1396
|
+
function analyzeCommentImpact(score, isEdited, isOp) {
|
|
1397
|
+
const insights = [
|
|
1398
|
+
...score > 100 ? ["Highly upvoted comment with significant community agreement"] : score < 0 ? ["Controversial or contested viewpoint"] : [],
|
|
1399
|
+
...isEdited ? ["Refined for clarity or accuracy"] : [],
|
|
1400
|
+
...isOp ? ["Author's perspective adds context to original post"] : []
|
|
1401
|
+
];
|
|
1402
|
+
return insights.length > 0 ? insights.join("\n - ") : "Standard engagement with discussion";
|
|
1403
|
+
}
|
|
1164
1404
|
function formatUserInfo(user) {
|
|
1165
1405
|
const accountAgeDays = (Date.now() / 1e3 - user.createdUtc) / 86400;
|
|
1166
1406
|
const karmaRatio = user.commentKarma / (user.linkKarma === 0 ? 1 : user.linkKarma);
|
|
@@ -1183,9 +1423,18 @@ function formatUserInfo(user) {
|
|
|
1183
1423
|
recommendations: getUserRecommendations(karmaRatio, user.isMod, accountAgeDays)
|
|
1184
1424
|
};
|
|
1185
1425
|
}
|
|
1426
|
+
const POST_CONTENT_MAX_LENGTH = 1e4;
|
|
1427
|
+
const COMMENT_CONTENT_MAX_LENGTH = 5e3;
|
|
1428
|
+
function truncateText(text, maxLength) {
|
|
1429
|
+
return text.length > maxLength ? `${text.substring(0, maxLength - 3)}...` : text;
|
|
1430
|
+
}
|
|
1431
|
+
function postContent(post) {
|
|
1432
|
+
const body = truncateText(post.selftext ?? "", POST_CONTENT_MAX_LENGTH);
|
|
1433
|
+
if (post.isSelf) return body;
|
|
1434
|
+
return [body, post.url ?? ""].filter((part) => part.length > 0).join("\n\n");
|
|
1435
|
+
}
|
|
1186
1436
|
function formatPostInfo(post) {
|
|
1187
1437
|
const contentType = post.isSelf ? "Text Post" : "Link Post";
|
|
1188
|
-
const content = post.isSelf ? post.selftext ?? "" : post.url ?? "";
|
|
1189
1438
|
const flags = [
|
|
1190
1439
|
...post.over18 ? ["NSFW"] : [],
|
|
1191
1440
|
...post.spoiler === true ? ["Spoiler"] : [],
|
|
@@ -1194,7 +1443,7 @@ function formatPostInfo(post) {
|
|
|
1194
1443
|
return {
|
|
1195
1444
|
title: post.title,
|
|
1196
1445
|
type: contentType,
|
|
1197
|
-
content:
|
|
1446
|
+
content: postContent(post),
|
|
1198
1447
|
author: post.author,
|
|
1199
1448
|
subreddit: post.subreddit,
|
|
1200
1449
|
stats: {
|
|
@@ -1241,10 +1490,30 @@ function formatSubredditInfo(subreddit) {
|
|
|
1241
1490
|
engagementTips: getSubredditEngagementTips(subreddit)
|
|
1242
1491
|
};
|
|
1243
1492
|
}
|
|
1244
|
-
|
|
1245
|
-
|
|
1493
|
+
function formatCommentInfo(comment, maxLength = COMMENT_CONTENT_MAX_LENGTH) {
|
|
1494
|
+
const flags = [...comment.edited ? ["Edited"] : [], ...comment.isSubmitter ? ["OP"] : []];
|
|
1495
|
+
return {
|
|
1496
|
+
author: comment.author,
|
|
1497
|
+
content: truncateText(comment.body, maxLength),
|
|
1498
|
+
stats: {
|
|
1499
|
+
score: comment.score,
|
|
1500
|
+
controversiality: comment.controversiality
|
|
1501
|
+
},
|
|
1502
|
+
context: {
|
|
1503
|
+
subreddit: comment.subreddit,
|
|
1504
|
+
thread: comment.submissionTitle
|
|
1505
|
+
},
|
|
1506
|
+
metadata: {
|
|
1507
|
+
posted: formatTimestamp(comment.createdUtc),
|
|
1508
|
+
flags: flags.length > 0 ? flags : ["None"]
|
|
1509
|
+
},
|
|
1510
|
+
link: `https://reddit.com${comment.permalink}`,
|
|
1511
|
+
commentAnalysis: analyzeCommentImpact(comment.score, comment.edited, comment.isSubmitter)
|
|
1512
|
+
};
|
|
1513
|
+
}
|
|
1514
|
+
// src/index.ts
|
|
1246
1515
|
dotenv.config({ quiet: true });
|
|
1247
|
-
const VERSION = "1.
|
|
1516
|
+
const VERSION = "1.7.0";
|
|
1248
1517
|
function validateUserAgent(userAgent, username) {
|
|
1249
1518
|
if (!/^[\w-]+:[\w-]+:[\d.]+ \(by \/u\/\w+\)$/.test(userAgent)) {
|
|
1250
1519
|
console.error("[Warning] User-Agent does not follow Reddit's recommended format");
|
|
@@ -1295,11 +1564,17 @@ function buildSafeModeConfig(safeMode) {
|
|
|
1295
1564
|
function unwrapClient() {
|
|
1296
1565
|
return getRedditClient().orThrow(/* @__PURE__ */ new Error("Reddit client not initialized"));
|
|
1297
1566
|
}
|
|
1298
|
-
|
|
1299
|
-
|
|
1567
|
+
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.";
|
|
1568
|
+
function sourceDisclaimer(page) {
|
|
1569
|
+
const notice = Option(page.notice).fold(() => "", (text) => `\n\n> **Note** — ${text}`);
|
|
1570
|
+
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.`;
|
|
1571
|
+
return page.source === "arctic" ? `${notice}${ARCHIVE_DISCLAIMER}` : notice;
|
|
1572
|
+
}
|
|
1573
|
+
function archiveDisclaimer(client) {
|
|
1574
|
+
return client.keyless ? ARCHIVE_DISCLAIMER : "";
|
|
1300
1575
|
}
|
|
1301
1576
|
function formatPostSummary(post, index, source) {
|
|
1302
|
-
const statsLines = source === "rss" ? [] : [`- Score: ${post.stats.score.toLocaleString()} (${(post.stats.upvoteRatio * 100).toFixed(1)}% upvoted)`, `- Comments: ${post.stats.comments.toLocaleString()}`];
|
|
1577
|
+
const statsLines = source === "rss" || source === "arctic" ? [] : [`- Score: ${post.stats.score.toLocaleString()} (${(post.stats.upvoteRatio * 100).toFixed(1)}% upvoted)`, `- Comments: ${post.stats.comments.toLocaleString()}`];
|
|
1303
1578
|
return [
|
|
1304
1579
|
`### ${index + 1}. ${post.title}`,
|
|
1305
1580
|
`- Author: u/${post.author}`,
|
|
@@ -1313,8 +1588,8 @@ function nextPageHint(after) {
|
|
|
1313
1588
|
}
|
|
1314
1589
|
function formatUserContent(heading, content) {
|
|
1315
1590
|
return `# ${heading}\n\n${content.posts.length === 0 ? "" : `## Posts (${content.posts.length})\n${content.posts.map((post, index) => `${index + 1}. ${post.title} — r/${post.subreddit}, score ${post.score.toLocaleString()} — https://reddit.com${post.permalink}`).join("\n")}\n\n`}${content.comments.length === 0 ? "" : `## Comments (${content.comments.length})\n${content.comments.map((comment, index) => {
|
|
1316
|
-
const
|
|
1317
|
-
return `${index + 1}. in r/${comment.subreddit}: ${
|
|
1591
|
+
const formatted = formatCommentInfo(comment, 200);
|
|
1592
|
+
return `${index + 1}. in r/${comment.subreddit}: ${formatted.content} — ${formatted.link}`;
|
|
1318
1593
|
}).join("\n")}\n\n`}${content.posts.length === 0 && content.comments.length === 0 ? "No items found.\n\n" : ""}`.trimEnd() + nextPageHint(content.after);
|
|
1319
1594
|
}
|
|
1320
1595
|
async function setupRedditClient() {
|
|
@@ -1382,8 +1657,9 @@ async function setupRedditClient() {
|
|
|
1382
1657
|
console.error(`[Setup] Authentication mode: ${authMode}`);
|
|
1383
1658
|
if (authMode === "anonymous") console.error("[Warning] REDDIT_AUTH_MODE=anonymous is deprecated; it is now an alias for auto without credentials.");
|
|
1384
1659
|
if (authMode === "anonymous" || !hasCredentials) {
|
|
1385
|
-
console.error("[Setup]
|
|
1386
|
-
console.error("[Setup]
|
|
1660
|
+
console.error("[Setup] Keyless mode — no OAuth credentials detected.");
|
|
1661
|
+
console.error("[Setup] Reads come from RSS feeds (ranked listings, until Reddit retires them 2026-11-13)");
|
|
1662
|
+
console.error("[Setup] and the Arctic Shift archive (a free third-party Reddit archive; scores lag).");
|
|
1387
1663
|
console.error("[Setup] Set REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET for full API access (100 req/min).");
|
|
1388
1664
|
console.error("[Setup] See: https://www.reddit.com/wiki/api");
|
|
1389
1665
|
} else {
|
|
@@ -1476,6 +1752,7 @@ server.addTool({
|
|
|
1476
1752
|
return Promise.resolve(`Reddit MCP Server Status:
|
|
1477
1753
|
- Server: ✓ Running
|
|
1478
1754
|
- Reddit Client: ${hasAuth} ${client.fold(() => "Not initialized", () => "Initialized")}
|
|
1755
|
+
- Read Source: ${client.fold(() => "Unknown", (c) => c.keyless ? "Keyless (RSS feeds + Arctic Shift archive; scores lag)" : "Reddit API (OAuth)")}
|
|
1479
1756
|
- Write Access: ${hasWriteAccess} ${hasWriteAccess === "✓" ? "Available" : "Read-only mode"}
|
|
1480
1757
|
- Version: ${VERSION}
|
|
1481
1758
|
|
|
@@ -1484,7 +1761,7 @@ Ready to handle Reddit API requests!`);
|
|
|
1484
1761
|
});
|
|
1485
1762
|
server.addTool({
|
|
1486
1763
|
name: "get_user_info",
|
|
1487
|
-
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;
|
|
1764
|
+
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.",
|
|
1488
1765
|
annotations: {
|
|
1489
1766
|
title: "Get User Info",
|
|
1490
1767
|
readOnlyHint: true,
|
|
@@ -1492,7 +1769,8 @@ server.addTool({
|
|
|
1492
1769
|
},
|
|
1493
1770
|
parameters: z.object({ username: z.string().describe("The target user's Reddit username, without the u/ prefix (e.g. 'spez', not 'u/spez').") }),
|
|
1494
1771
|
execute: async (args) => {
|
|
1495
|
-
|
|
1772
|
+
const client = unwrapClient();
|
|
1773
|
+
return (await client.getUser(args.username)).fold((err) => {
|
|
1496
1774
|
throw new Error(`Failed to get user info: ${err.message}`);
|
|
1497
1775
|
}, (user) => {
|
|
1498
1776
|
const formattedUser = formatUserInfo(user);
|
|
@@ -1504,15 +1782,15 @@ server.addTool({
|
|
|
1504
1782
|
- Comment Karma: ${formattedUser.karma.commentKarma.toLocaleString()}
|
|
1505
1783
|
- Post Karma: ${formattedUser.karma.postKarma.toLocaleString()}
|
|
1506
1784
|
- Total Karma: ${formattedUser.karma.totalKarma.toLocaleString()}
|
|
1507
|
-
- Account Status: ${formattedUser.accountStatus.join(", ")}
|
|
1508
|
-
- Account Created: ${formattedUser.accountCreated}
|
|
1785
|
+
- Account Status: ${client.keyless ? "Unknown (not in the archive)" : formattedUser.accountStatus.join(", ")}
|
|
1786
|
+
- Account Created: ${client.keyless && user.createdUtc === 0 ? "Unknown (no archived activity)" : formattedUser.accountCreated}
|
|
1509
1787
|
- Profile URL: ${formattedUser.profileUrl}
|
|
1510
1788
|
|
|
1511
1789
|
## Activity Analysis
|
|
1512
1790
|
- ${formattedUser.activityAnalysis.replace(/\n {2}- /g, "\n- ")}
|
|
1513
1791
|
|
|
1514
1792
|
## Recommendations
|
|
1515
|
-
- ${formattedUser.recommendations.replace(/\n {2}- /g, "\n- ")}`;
|
|
1793
|
+
- ${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)}`;
|
|
1516
1794
|
});
|
|
1517
1795
|
}
|
|
1518
1796
|
});
|
|
@@ -1588,7 +1866,7 @@ server.addTool({
|
|
|
1588
1866
|
});
|
|
1589
1867
|
server.addTool({
|
|
1590
1868
|
name: "get_user_posts",
|
|
1591
|
-
description: "Get posts submitted by a specific user, with sort (new/hot/top) and time filter. Read-only;
|
|
1869
|
+
description: "Get posts submitted by a specific user, with sort (new/hot/top) and time filter. Read-only; works without credentials via the Arctic Shift archive (scores lag). Returns a page of posts (title, subreddit, score, upvote ratio, comment count, permalink) plus an `after` cursor for paging. Use get_user_comments for their comments, or get_user_info for karma/profile stats. Do NOT use this to search a subreddit — use search_reddit or browse_subreddit.",
|
|
1592
1870
|
annotations: {
|
|
1593
1871
|
title: "Get User Posts",
|
|
1594
1872
|
readOnlyHint: true,
|
|
@@ -1634,13 +1912,13 @@ server.addTool({
|
|
|
1634
1912
|
}).join("\n\n");
|
|
1635
1913
|
return `# Posts by u/${args.username} (${args.sort} - ${args.time_filter})
|
|
1636
1914
|
|
|
1637
|
-
${postSummaries}${nextPageHint(page.after)}`;
|
|
1915
|
+
${postSummaries}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
|
|
1638
1916
|
});
|
|
1639
1917
|
}
|
|
1640
1918
|
});
|
|
1641
1919
|
server.addTool({
|
|
1642
1920
|
name: "get_user_comments",
|
|
1643
|
-
description: "Get comments made by a specific user, with sort (new/hot/top) and time filter. Read-only;
|
|
1921
|
+
description: "Get comments made by a specific user, with sort (new/hot/top) and time filter. Read-only; works without credentials via the Arctic Shift archive (scores lag). Returns a page of comments (subreddit, parent post title, body excerpt, score, permalink) plus an `after` cursor. Use get_user_posts for their submissions, or get_user_info for karma/profile stats. Do NOT use this to read one post's thread — use get_post_comments.",
|
|
1644
1922
|
annotations: {
|
|
1645
1923
|
title: "Get User Comments",
|
|
1646
1924
|
readOnlyHint: true,
|
|
@@ -1676,26 +1954,26 @@ server.addTool({
|
|
|
1676
1954
|
const comments = page.items;
|
|
1677
1955
|
if (comments.length === 0) return `No comments found for u/${args.username} with the specified filters.`;
|
|
1678
1956
|
const commentSummaries = comments.map((comment, index) => {
|
|
1679
|
-
const
|
|
1957
|
+
const formatted = formatCommentInfo(comment, 300);
|
|
1680
1958
|
const flags = [...comment.edited ? ["*(edited)*"] : [], ...comment.isSubmitter ? ["**OP**"] : []];
|
|
1681
1959
|
return `### ${index + 1}. Comment ${flags.join(" ")}
|
|
1682
1960
|
In r/${comment.subreddit} on "${comment.submissionTitle}"
|
|
1683
1961
|
|
|
1684
|
-
> ${
|
|
1962
|
+
> ${formatted.content}
|
|
1685
1963
|
|
|
1686
1964
|
- Score: ${comment.score.toLocaleString()}
|
|
1687
1965
|
- Posted: ${(/* @__PURE__ */ new Date(comment.createdUtc * 1e3)).toLocaleString()}
|
|
1688
|
-
- Link:
|
|
1966
|
+
- Link: ${formatted.link}`;
|
|
1689
1967
|
}).join("\n\n");
|
|
1690
1968
|
return `# Comments by u/${args.username} (${args.sort} - ${args.time_filter})
|
|
1691
1969
|
|
|
1692
|
-
${commentSummaries}${nextPageHint(page.after)}`;
|
|
1970
|
+
${commentSummaries}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
|
|
1693
1971
|
});
|
|
1694
1972
|
}
|
|
1695
1973
|
});
|
|
1696
1974
|
server.addTool({
|
|
1697
1975
|
name: "get_reddit_post",
|
|
1698
|
-
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;
|
|
1976
|
+
description: "Get a single post by subreddit + post id: title, author, self-text or link content, score, upvote ratio, comment count, flair/flags, and an engagement analysis. Read-only; works without credentials via the Arctic Shift archive (scores lag). Returns the post only — use get_post_comments for its comment thread. Do NOT use this to list a subreddit's posts (use browse_subreddit / get_top_posts) or to find posts by keyword (use search_reddit).",
|
|
1699
1977
|
annotations: {
|
|
1700
1978
|
title: "Get Reddit Post",
|
|
1701
1979
|
readOnlyHint: true,
|
|
@@ -1706,7 +1984,8 @@ server.addTool({
|
|
|
1706
1984
|
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.")
|
|
1707
1985
|
}),
|
|
1708
1986
|
execute: async (args) => {
|
|
1709
|
-
|
|
1987
|
+
const client = unwrapClient();
|
|
1988
|
+
return (await client.getPost(args.post_id, args.subreddit)).fold((err) => {
|
|
1710
1989
|
throw new Error(`Failed to get post: ${err.message}`);
|
|
1711
1990
|
}, (post) => {
|
|
1712
1991
|
const formattedPost = formatPostInfo(post);
|
|
@@ -1738,13 +2017,13 @@ ${formattedPost.content}
|
|
|
1738
2017
|
- ${formattedPost.engagementAnalysis.replace(/\n {2}- /g, "\n- ")}
|
|
1739
2018
|
|
|
1740
2019
|
## Best Time to Engage
|
|
1741
|
-
${formattedPost.bestTimeToEngage}`;
|
|
2020
|
+
${formattedPost.bestTimeToEngage}${archiveDisclaimer(client)}`;
|
|
1742
2021
|
});
|
|
1743
2022
|
}
|
|
1744
2023
|
});
|
|
1745
2024
|
server.addTool({
|
|
1746
2025
|
name: "get_top_posts",
|
|
1747
|
-
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
|
|
2026
|
+
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.",
|
|
1748
2027
|
annotations: {
|
|
1749
2028
|
title: "Get Top Posts",
|
|
1750
2029
|
readOnlyHint: true,
|
|
@@ -1772,13 +2051,13 @@ server.addTool({
|
|
|
1772
2051
|
const postSummaries = posts.map(formatPostInfo).map((post, index) => formatPostSummary(post, index, page.source)).join("\n\n");
|
|
1773
2052
|
return `# Top Posts from ${Option(args.subreddit).fold(() => "Home Feed", (sr) => `r/${sr}`)} (${args.time_filter})
|
|
1774
2053
|
|
|
1775
|
-
${postSummaries}${nextPageHint(page.after)}${
|
|
2054
|
+
${postSummaries}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
|
|
1776
2055
|
});
|
|
1777
2056
|
}
|
|
1778
2057
|
});
|
|
1779
2058
|
server.addTool({
|
|
1780
2059
|
name: "browse_subreddit",
|
|
1781
|
-
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
|
|
2060
|
+
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.",
|
|
1782
2061
|
annotations: {
|
|
1783
2062
|
title: "Browse Subreddit",
|
|
1784
2063
|
readOnlyHint: true,
|
|
@@ -1816,13 +2095,13 @@ server.addTool({
|
|
|
1816
2095
|
const heading = location === "home feed" ? "Home Feed" : location;
|
|
1817
2096
|
return `# ${args.sort} posts from ${heading} (${args.sort}${timeSuffix})
|
|
1818
2097
|
|
|
1819
|
-
${postSummaries}${nextPageHint(page.after)}${
|
|
2098
|
+
${postSummaries}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
|
|
1820
2099
|
});
|
|
1821
2100
|
}
|
|
1822
2101
|
});
|
|
1823
2102
|
server.addTool({
|
|
1824
2103
|
name: "get_subreddit_info",
|
|
1825
|
-
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;
|
|
2104
|
+
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'.",
|
|
1826
2105
|
annotations: {
|
|
1827
2106
|
title: "Get Subreddit Info",
|
|
1828
2107
|
readOnlyHint: true,
|
|
@@ -1830,7 +2109,8 @@ server.addTool({
|
|
|
1830
2109
|
},
|
|
1831
2110
|
parameters: z.object({ subreddit_name: z.string().describe("The subreddit name, without the r/ prefix (e.g. 'askscience').") }),
|
|
1832
2111
|
execute: async (args) => {
|
|
1833
|
-
|
|
2112
|
+
const client = unwrapClient();
|
|
2113
|
+
return (await client.getSubredditInfo(args.subreddit_name)).fold((err) => {
|
|
1834
2114
|
throw new Error(`Failed to get subreddit info: ${err.message}`);
|
|
1835
2115
|
}, (subreddit) => {
|
|
1836
2116
|
const formattedSubreddit = formatSubredditInfo(subreddit);
|
|
@@ -1860,13 +2140,13 @@ ${formattedSubreddit.description.full}
|
|
|
1860
2140
|
- ${formattedSubreddit.communityAnalysis.replace(/\n {2}- /g, "\n- ")}
|
|
1861
2141
|
|
|
1862
2142
|
## Engagement Tips
|
|
1863
|
-
- ${formattedSubreddit.engagementTips.replace(/\n {2}- /g, "\n- ")}`;
|
|
2143
|
+
- ${formattedSubreddit.engagementTips.replace(/\n {2}- /g, "\n- ")}${archiveDisclaimer(client)}`;
|
|
1864
2144
|
});
|
|
1865
2145
|
}
|
|
1866
2146
|
});
|
|
1867
2147
|
server.addTool({
|
|
1868
2148
|
name: "get_subreddit_rules",
|
|
1869
|
-
description: "Get a subreddit's posting rules (each rule's name, what it applies to, and its description). Read-only;
|
|
2149
|
+
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.",
|
|
1870
2150
|
annotations: {
|
|
1871
2151
|
title: "Get Subreddit Rules",
|
|
1872
2152
|
readOnlyHint: true,
|
|
@@ -1874,7 +2154,8 @@ server.addTool({
|
|
|
1874
2154
|
},
|
|
1875
2155
|
parameters: z.object({ subreddit_name: z.string().describe("The subreddit name, without the r/ prefix (e.g. 'AskReddit').") }),
|
|
1876
2156
|
execute: async (args) => {
|
|
1877
|
-
|
|
2157
|
+
const client = unwrapClient();
|
|
2158
|
+
return (await client.getSubredditRules(args.subreddit_name)).fold((err) => {
|
|
1878
2159
|
throw new Error(`Failed to get subreddit rules: ${err.message}`);
|
|
1879
2160
|
}, (rules) => {
|
|
1880
2161
|
if (rules.length === 0) return `r/${args.subreddit_name} has no listed subreddit-specific rules.`;
|
|
@@ -1885,7 +2166,7 @@ server.addTool({
|
|
|
1885
2166
|
}).join("\n\n");
|
|
1886
2167
|
return `# Posting Rules for r/${args.subreddit_name}
|
|
1887
2168
|
|
|
1888
|
-
${ruleList}`;
|
|
2169
|
+
${ruleList}${archiveDisclaimer(client)}`;
|
|
1889
2170
|
});
|
|
1890
2171
|
}
|
|
1891
2172
|
});
|
|
@@ -1934,7 +2215,7 @@ ${trendingSubreddits.map((subreddit, index) => `${index + 1}. r/${subreddit}`).j
|
|
|
1934
2215
|
});
|
|
1935
2216
|
server.addTool({
|
|
1936
2217
|
name: "search_reddit",
|
|
1937
|
-
description: "Search Reddit for posts — or subreddits/users via `type` — optionally scoped to one subreddit, with sort and time filters. Read-only
|
|
2218
|
+
description: "Search Reddit for posts — or subreddits/users via `type` — optionally scoped to one subreddit, with sort and time filters. Read-only. Without credentials it uses the Arctic Shift archive, which needs `subreddit` for post search, matches subreddit names by prefix, and cannot search users. Returns a page of results (title, subreddit, author, score, comments, link) plus an `after` cursor for paging. Use this to find content by keyword; use browse_subreddit / get_top_posts to list a known subreddit's feed instead.",
|
|
1938
2219
|
annotations: {
|
|
1939
2220
|
title: "Search Reddit",
|
|
1940
2221
|
readOnlyHint: true,
|
|
@@ -1999,7 +2280,7 @@ server.addTool({
|
|
|
1999
2280
|
|
|
2000
2281
|
Sorted by: ${args.sort} | Time: ${args.time_filter} | Type: ${args.type}
|
|
2001
2282
|
|
|
2002
|
-
${searchResults}${nextPageHint(page.after)}`;
|
|
2283
|
+
${searchResults}${nextPageHint(page.after)}${sourceDisclaimer(page)}`;
|
|
2003
2284
|
});
|
|
2004
2285
|
}
|
|
2005
2286
|
});
|
|
@@ -2218,7 +2499,7 @@ ${args.thing_id} has been removed from your saved items.`);
|
|
|
2218
2499
|
});
|
|
2219
2500
|
server.addTool({
|
|
2220
2501
|
name: "get_post_comments",
|
|
2221
|
-
description: "Get the comment thread for a post (by post id + subreddit), sorted best/top/new/controversial/old/qa. Read-only;
|
|
2502
|
+
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.",
|
|
2222
2503
|
annotations: {
|
|
2223
2504
|
title: "Get Post Comments",
|
|
2224
2505
|
readOnlyHint: true,
|
|
@@ -2245,18 +2526,18 @@ server.addTool({
|
|
|
2245
2526
|
limit: args.limit
|
|
2246
2527
|
})).fold((err) => {
|
|
2247
2528
|
throw new Error(`Failed to get comments: ${err.message}`);
|
|
2248
|
-
}, ({ post, comments }) => {
|
|
2529
|
+
}, ({ post, comments, moreIds }) => {
|
|
2530
|
+
const statsLine = client.keyless ? "" : `- Score: ${post.score.toLocaleString()} | Comments: ${post.numComments.toLocaleString()}\n`;
|
|
2249
2531
|
const header = `# Comments for: ${post.title}
|
|
2250
2532
|
|
|
2251
2533
|
**Post by u/${post.author} in r/${post.subreddit}**
|
|
2252
|
-
-
|
|
2253
|
-
- Posted: ${(/* @__PURE__ */ new Date(post.createdUtc * 1e3)).toLocaleString()}
|
|
2534
|
+
${statsLine}- Posted: ${(/* @__PURE__ */ new Date(post.createdUtc * 1e3)).toLocaleString()}
|
|
2254
2535
|
|
|
2255
2536
|
---
|
|
2256
2537
|
|
|
2257
2538
|
`;
|
|
2258
2539
|
if (comments.length === 0) return `${header}No comments found for this post.`;
|
|
2259
|
-
|
|
2540
|
+
const commentSummaries = comments.map((comment) => {
|
|
2260
2541
|
const indent = "└─".repeat(Math.min(comment.depth ?? 0, 3));
|
|
2261
2542
|
const authorBadge = comment.isSubmitter ? " **[OP]**" : "";
|
|
2262
2543
|
const editedBadge = comment.edited ? " *(edited)*" : "";
|
|
@@ -2266,12 +2547,15 @@ ${comment.body}
|
|
|
2266
2547
|
|
|
2267
2548
|
---`;
|
|
2268
2549
|
}).join("\n\n");
|
|
2550
|
+
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)" : ""}` : "";
|
|
2551
|
+
const sortNote = client.keyless && args.sort !== "best" ? `\n\n> sort="${args.sort}" is not applied to archive comments.` : "";
|
|
2552
|
+
return header + commentSummaries + moreHint + sortNote + archiveDisclaimer(client);
|
|
2269
2553
|
});
|
|
2270
2554
|
}
|
|
2271
2555
|
});
|
|
2272
2556
|
server.addTool({
|
|
2273
2557
|
name: "get_more_comments",
|
|
2274
|
-
description: "Expand truncated 'load more comments' stubs in a thread. Read-only;
|
|
2558
|
+
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.",
|
|
2275
2559
|
annotations: {
|
|
2276
2560
|
title: "Get More Comments",
|
|
2277
2561
|
readOnlyHint: true,
|
|
@@ -2282,22 +2566,23 @@ server.addTool({
|
|
|
2282
2566
|
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).")
|
|
2283
2567
|
}),
|
|
2284
2568
|
execute: async (args) => {
|
|
2285
|
-
|
|
2569
|
+
const client = unwrapClient();
|
|
2570
|
+
return (await client.getMoreComments(args.link_id, args.comment_ids)).fold((err) => {
|
|
2286
2571
|
throw new Error(`Failed to expand comments: ${err.message}`);
|
|
2287
2572
|
}, (comments) => {
|
|
2288
2573
|
if (comments.length === 0) return "No additional comments were returned for those ids.";
|
|
2289
2574
|
const commentList = comments.map((comment, index) => {
|
|
2290
|
-
const
|
|
2575
|
+
const formatted = formatCommentInfo(comment, 300);
|
|
2291
2576
|
const flags = [...comment.edited ? ["*(edited)*"] : [], ...comment.isSubmitter ? ["**OP**"] : []];
|
|
2292
2577
|
return `### ${index + 1}. u/${comment.author} ${flags.join(" ")}
|
|
2293
|
-
> ${
|
|
2578
|
+
> ${formatted.content}
|
|
2294
2579
|
|
|
2295
2580
|
- Score: ${comment.score.toLocaleString()}
|
|
2296
|
-
- Link:
|
|
2581
|
+
- Link: ${formatted.link}`;
|
|
2297
2582
|
}).join("\n\n");
|
|
2298
2583
|
return `# Expanded Comments (${comments.length})
|
|
2299
2584
|
|
|
2300
|
-
${commentList}`;
|
|
2585
|
+
${commentList}${archiveDisclaimer(client)}`;
|
|
2301
2586
|
});
|
|
2302
2587
|
}
|
|
2303
2588
|
});
|
|
@@ -2320,6 +2605,11 @@ async function main() {
|
|
|
2320
2605
|
console.error(`[Setup] SSE endpoint available at http://${host}:${port}/sse`);
|
|
2321
2606
|
} else {
|
|
2322
2607
|
console.error("[Setup] Starting in stdio mode");
|
|
2608
|
+
if (process.stdin.isTTY) {
|
|
2609
|
+
console.error("[Setup] ⚠ stdin is a terminal. This server speaks MCP JSON-RPC over stdio and expects an MCP client (Claude Desktop, Claude Code, MCP Inspector) on the other end — typed input will cause JSON parse errors.");
|
|
2610
|
+
console.error("[Setup] Test interactively: npx @modelcontextprotocol/inspector npx reddit-mcp-server");
|
|
2611
|
+
console.error("[Setup] Or run as HTTP: TRANSPORT_TYPE=httpStream npx reddit-mcp-server");
|
|
2612
|
+
}
|
|
2323
2613
|
await server.start({ transportType: "stdio" });
|
|
2324
2614
|
}
|
|
2325
2615
|
}
|
|
@@ -2332,7 +2622,6 @@ process.on("SIGTERM", () => {
|
|
|
2332
2622
|
process.exit(0);
|
|
2333
2623
|
});
|
|
2334
2624
|
main().catch(console.error);
|
|
2335
|
-
//#endregion
|
|
2336
2625
|
export {};
|
|
2337
2626
|
|
|
2338
2627
|
//# sourceMappingURL=index.js.map
|