reddit-mcp-server 1.7.2 → 2.0.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/CHANGELOG.md +140 -0
- package/README.md +73 -19
- package/dist/bin.js +12 -6
- package/dist/bin.js.map +1 -1
- package/dist/index.js +101 -125
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import crypto from "crypto";
|
|
2
2
|
import dotenv from "dotenv";
|
|
3
|
-
import { FastMCP } from "fastmcp";
|
|
4
3
|
import { Left, Option, Right, Try } from "functype";
|
|
4
|
+
import { createServer, getRequestHeader } from "somamcp/node";
|
|
5
5
|
import { z } from "zod";
|
|
6
6
|
import { XMLParser } from "fast-xml-parser";
|
|
7
7
|
// src/client/errors.ts
|
|
@@ -1363,6 +1363,22 @@ function initializeRedditClient(config) {
|
|
|
1363
1363
|
function getRedditClient() {
|
|
1364
1364
|
return clientHolder.instance;
|
|
1365
1365
|
}
|
|
1366
|
+
// src/utils/env.ts
|
|
1367
|
+
/**
|
|
1368
|
+
* Read an environment variable, treating an empty or whitespace-only value as unset.
|
|
1369
|
+
*
|
|
1370
|
+
* dotenv turns a `KEY=` line into an empty string, so a copied `.env.example` would
|
|
1371
|
+
* otherwise read as configured: `OAUTH_TOKEN=` locked out every HTTP client, and
|
|
1372
|
+
* `REDDIT_AUTH_MODE=authenticated` with blank credentials started keyless instead of failing.
|
|
1373
|
+
* The value is returned as written; it is not trimmed, so a password may contain spaces.
|
|
1374
|
+
*/
|
|
1375
|
+
function readEnv(name, env = process.env) {
|
|
1376
|
+
return Option(env[name]).filter((value) => value.trim() !== "");
|
|
1377
|
+
}
|
|
1378
|
+
/** True when both `REDDIT_USERNAME` and `REDDIT_PASSWORD` are set to non-blank values. */
|
|
1379
|
+
function hasUserCredentials(env = process.env) {
|
|
1380
|
+
return readEnv("REDDIT_USERNAME", env).isSome() && readEnv("REDDIT_PASSWORD", env).isSome();
|
|
1381
|
+
}
|
|
1366
1382
|
// src/utils/formatters.ts
|
|
1367
1383
|
function formatTimestamp(timestamp) {
|
|
1368
1384
|
return Try(() => {
|
|
@@ -1532,7 +1548,7 @@ function formatCommentInfo(comment, maxLength = COMMENT_CONTENT_MAX_LENGTH) {
|
|
|
1532
1548
|
}
|
|
1533
1549
|
// src/index.ts
|
|
1534
1550
|
dotenv.config({ quiet: true });
|
|
1535
|
-
const VERSION = "
|
|
1551
|
+
const VERSION = "2.0.1";
|
|
1536
1552
|
function validateUserAgent(userAgent, username) {
|
|
1537
1553
|
if (!/^[\w-]+:[\w-]+:[\d.]+ \(by \/u\/\w+\)$/.test(userAgent)) {
|
|
1538
1554
|
console.error("[Warning] User-Agent does not follow Reddit's recommended format");
|
|
@@ -1580,6 +1596,15 @@ function buildSafeModeConfig(safeMode) {
|
|
|
1580
1596
|
};
|
|
1581
1597
|
}
|
|
1582
1598
|
}
|
|
1599
|
+
function toolError(text) {
|
|
1600
|
+
return {
|
|
1601
|
+
content: [{
|
|
1602
|
+
text,
|
|
1603
|
+
type: "text"
|
|
1604
|
+
}],
|
|
1605
|
+
isError: true
|
|
1606
|
+
};
|
|
1607
|
+
}
|
|
1583
1608
|
function unwrapClient() {
|
|
1584
1609
|
return getRedditClient().orThrow(/* @__PURE__ */ new Error("Reddit client not initialized"));
|
|
1585
1610
|
}
|
|
@@ -1643,13 +1668,13 @@ function formatUserContent(heading, content) {
|
|
|
1643
1668
|
}).join("\n")}\n\n`}${content.posts.length === 0 && content.comments.length === 0 ? "No items found.\n\n" : ""}`.trimEnd() + nextPageHint(content.after);
|
|
1644
1669
|
}
|
|
1645
1670
|
async function setupRedditClient() {
|
|
1646
|
-
const clientId =
|
|
1647
|
-
const clientSecret =
|
|
1648
|
-
const customUserAgent =
|
|
1649
|
-
const username =
|
|
1650
|
-
const password =
|
|
1651
|
-
const authMode =
|
|
1652
|
-
const safeMode =
|
|
1671
|
+
const clientId = readEnv("REDDIT_CLIENT_ID").orUndefined();
|
|
1672
|
+
const clientSecret = readEnv("REDDIT_CLIENT_SECRET").orUndefined();
|
|
1673
|
+
const customUserAgent = readEnv("REDDIT_USER_AGENT").orUndefined();
|
|
1674
|
+
const username = readEnv("REDDIT_USERNAME").orUndefined();
|
|
1675
|
+
const password = readEnv("REDDIT_PASSWORD").orUndefined();
|
|
1676
|
+
const authMode = readEnv("REDDIT_AUTH_MODE").orElse("auto");
|
|
1677
|
+
const safeMode = readEnv("REDDIT_SAFE_MODE").orElse("standard");
|
|
1653
1678
|
if (") : ""
|
|
1682
1707
|
};
|
|
1683
|
-
const cacheEnabled = (
|
|
1684
|
-
const cacheMaxMb = Number(
|
|
1708
|
+
const cacheEnabled = readEnv("REDDIT_CACHE").orElse("on") !== "off";
|
|
1709
|
+
const cacheMaxMb = Number(readEnv("REDDIT_CACHE_MAX_MB").orElse("50"));
|
|
1685
1710
|
const cacheConfig = {
|
|
1686
1711
|
enabled: cacheEnabled,
|
|
1687
1712
|
maxBytes: (Number.isFinite(cacheMaxMb) && cacheMaxMb > 0 ? cacheMaxMb : 50) * 1024 * 1024
|
|
1688
1713
|
};
|
|
1689
|
-
const maxRetriesRaw = Number(
|
|
1714
|
+
const maxRetriesRaw = Number(readEnv("REDDIT_MAX_RETRIES").orElse("3"));
|
|
1690
1715
|
const client = initializeRedditClient({
|
|
1691
1716
|
clientId: clientId ?? "",
|
|
1692
1717
|
clientSecret: clientSecret ?? "",
|
|
@@ -1710,8 +1735,9 @@ async function setupRedditClient() {
|
|
|
1710
1735
|
console.error("[Setup] Keyless mode — no OAuth credentials detected.");
|
|
1711
1736
|
console.error("[Setup] Reads come from RSS feeds (ranked listings, until Reddit retires them 2026-11-13)");
|
|
1712
1737
|
console.error("[Setup] and the Arctic Shift archive (a free third-party Reddit archive; scores lag).");
|
|
1713
|
-
console.error("[Setup]
|
|
1714
|
-
console.error("[Setup]
|
|
1738
|
+
console.error("[Setup] Existing REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET still give live data (60-100 req/min).");
|
|
1739
|
+
console.error("[Setup] Reddit takes no new API access requests and closes its public API in March 2027.");
|
|
1740
|
+
console.error("[Setup] See: https://github.com/jordanburke/reddit-mcp-server#reddit-is-closing-its-public-api");
|
|
1715
1741
|
} else {
|
|
1716
1742
|
console.error("[Setup] Testing Reddit API connection...");
|
|
1717
1743
|
if (!await client.checkAuthentication()) {
|
|
@@ -1740,9 +1766,20 @@ async function setupRedditClient() {
|
|
|
1740
1766
|
console.error("[Setup] For Reddit policy compliance, consider REDDIT_BOT_DISCLOSURE=auto");
|
|
1741
1767
|
}
|
|
1742
1768
|
}
|
|
1743
|
-
const
|
|
1744
|
-
|
|
1745
|
-
|
|
1769
|
+
const configuredOauthToken = readEnv("OAUTH_TOKEN");
|
|
1770
|
+
const oauthToken = configuredOauthToken.orElse(crypto.randomBytes(32).toString("hex"));
|
|
1771
|
+
if (readEnv("OAUTH_ENABLED").orElse("false") === "true" && configuredOauthToken.isNone()) console.error(`[Auth] Generated OAuth token: ${oauthToken}`);
|
|
1772
|
+
function authenticateBearer(request) {
|
|
1773
|
+
const authHeader = getRequestHeader(request, "authorization");
|
|
1774
|
+
if (!(authHeader === null || authHeader === void 0 ? void 0 : authHeader.startsWith("Bearer "))) return Promise.reject(new Response(null, { status: 401 }));
|
|
1775
|
+
const tokenHash = crypto.createHash("sha256").update(Buffer.from(authHeader.slice(7))).digest();
|
|
1776
|
+
const expectedHash = crypto.createHash("sha256").update(Buffer.from(oauthToken)).digest();
|
|
1777
|
+
if (!crypto.timingSafeEqual(tokenHash, expectedHash)) return Promise.reject(new Response(null, { status: 403 }));
|
|
1778
|
+
return Promise.resolve({ authenticated: true });
|
|
1779
|
+
}
|
|
1780
|
+
const transportType = readEnv("TRANSPORT_TYPE").orElse("stdio");
|
|
1781
|
+
const useHttp = transportType === "httpStream" || transportType === "http";
|
|
1782
|
+
const server = createServer({
|
|
1746
1783
|
name: "reddit-mcp-server",
|
|
1747
1784
|
version: VERSION,
|
|
1748
1785
|
instructions: `A comprehensive Reddit MCP server that provides tools for interacting with Reddit API.
|
|
@@ -1768,23 +1805,11 @@ IMPORTANT - Reddit Responsible Builder Policy compliance:
|
|
|
1768
1805
|
- All bot-generated content must clearly disclose its automated nature
|
|
1769
1806
|
- Bots must NOT send private/direct messages without explicit user consent
|
|
1770
1807
|
For details: https://support.reddithelp.com/hc/en-us/articles/42728983564564-Responsible-Builder-Policy`,
|
|
1771
|
-
...
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
});
|
|
1777
|
-
const token = authHeader.slice(7);
|
|
1778
|
-
const tokenBuffer = Buffer.from(token);
|
|
1779
|
-
const expectedBuffer = Buffer.from(oauthToken);
|
|
1780
|
-
const tokenHash = crypto.createHash("sha256").update(tokenBuffer).digest();
|
|
1781
|
-
const expectedHash = crypto.createHash("sha256").update(expectedBuffer).digest();
|
|
1782
|
-
if (!crypto.timingSafeEqual(tokenHash, expectedHash)) throw new Response(null, {
|
|
1783
|
-
status: 403,
|
|
1784
|
-
statusText: "Invalid token"
|
|
1785
|
-
});
|
|
1786
|
-
return Promise.resolve({ authenticated: true });
|
|
1787
|
-
} }
|
|
1808
|
+
...useHttp && readEnv("OAUTH_ENABLED").orElse("false") === "true" ? { authenticate: authenticateBearer } : {},
|
|
1809
|
+
enableIntrospection: false,
|
|
1810
|
+
enableInfoEndpoint: false,
|
|
1811
|
+
enableDashboard: false,
|
|
1812
|
+
streamKeepalive: { enabled: useHttp }
|
|
1788
1813
|
});
|
|
1789
1814
|
server.addTool({
|
|
1790
1815
|
name: "test_reddit_mcp_server",
|
|
@@ -1798,7 +1823,7 @@ server.addTool({
|
|
|
1798
1823
|
execute: () => {
|
|
1799
1824
|
const client = getRedditClient();
|
|
1800
1825
|
const hasAuth = client.fold(() => "✗", () => "✓");
|
|
1801
|
-
const hasWriteAccess =
|
|
1826
|
+
const hasWriteAccess = hasUserCredentials() ? "✓" : "✗";
|
|
1802
1827
|
return Promise.resolve(`Reddit MCP Server Status:
|
|
1803
1828
|
- Server: ✓ Running
|
|
1804
1829
|
- Reddit Client: ${hasAuth} ${client.fold(() => "Not initialized", () => "Initialized")}
|
|
@@ -1820,9 +1845,7 @@ server.addTool({
|
|
|
1820
1845
|
parameters: z.object({ username: z.string().describe("The target user's Reddit username, without the u/ prefix (e.g. 'spez', not 'u/spez').") }),
|
|
1821
1846
|
execute: async (args) => {
|
|
1822
1847
|
const client = unwrapClient();
|
|
1823
|
-
return (await client.getUser(args.username)).fold((err) => {
|
|
1824
|
-
throw new Error(`Failed to get user info: ${err.message}`);
|
|
1825
|
-
}, (user) => {
|
|
1848
|
+
return (await client.getUser(args.username)).fold((err) => toolError(`Failed to get user info: ${err.message}`), (user) => {
|
|
1826
1849
|
const formattedUser = formatUserInfo(user);
|
|
1827
1850
|
return `# User Information: u/${formattedUser.username}
|
|
1828
1851
|
|
|
@@ -1854,9 +1877,7 @@ server.addTool({
|
|
|
1854
1877
|
},
|
|
1855
1878
|
parameters: z.object({}),
|
|
1856
1879
|
execute: async () => {
|
|
1857
|
-
return (await unwrapClient().getMe()).fold((err) => {
|
|
1858
|
-
throw new Error(`Failed to get authenticated user: ${err.message}`);
|
|
1859
|
-
}, (user) => {
|
|
1880
|
+
return (await unwrapClient().getMe()).fold((err) => toolError(`Failed to get authenticated user: ${err.message}`), (user) => {
|
|
1860
1881
|
const formattedUser = formatUserInfo(user);
|
|
1861
1882
|
return `# Your Account: u/${formattedUser.username}
|
|
1862
1883
|
|
|
@@ -1888,9 +1909,7 @@ server.addTool({
|
|
|
1888
1909
|
return (await unwrapClient().getMyOverview({
|
|
1889
1910
|
limit: args.limit,
|
|
1890
1911
|
after: args.after
|
|
1891
|
-
})).fold((err) => {
|
|
1892
|
-
throw new Error(`Failed to get your overview: ${err.message}`);
|
|
1893
|
-
}, (content) => formatUserContent("Your Overview", content));
|
|
1912
|
+
})).fold((err) => toolError(`Failed to get your overview: ${err.message}`), (content) => formatUserContent("Your Overview", content));
|
|
1894
1913
|
}
|
|
1895
1914
|
});
|
|
1896
1915
|
server.addTool({
|
|
@@ -1909,9 +1928,7 @@ server.addTool({
|
|
|
1909
1928
|
return (await unwrapClient().getMySaved({
|
|
1910
1929
|
limit: args.limit,
|
|
1911
1930
|
after: args.after
|
|
1912
|
-
})).fold((err) => {
|
|
1913
|
-
throw new Error(`Failed to get saved content: ${err.message}`);
|
|
1914
|
-
}, (content) => formatUserContent("Your Saved Content", content));
|
|
1931
|
+
})).fold((err) => toolError(`Failed to get saved content: ${err.message}`), (content) => formatUserContent("Your Saved Content", content));
|
|
1915
1932
|
}
|
|
1916
1933
|
});
|
|
1917
1934
|
server.addTool({
|
|
@@ -1946,9 +1963,7 @@ server.addTool({
|
|
|
1946
1963
|
timeFilter: args.time_filter,
|
|
1947
1964
|
limit: args.limit,
|
|
1948
1965
|
after: args.after
|
|
1949
|
-
})).fold((err) => {
|
|
1950
|
-
throw new Error(`Failed to get user posts: ${err.message}`);
|
|
1951
|
-
}, (page) => {
|
|
1966
|
+
})).fold((err) => toolError(`Failed to get user posts: ${err.message}`), (page) => {
|
|
1952
1967
|
const posts = page.items;
|
|
1953
1968
|
if (posts.length === 0) return `No posts found for u/${args.username} with the specified filters.`;
|
|
1954
1969
|
const postSummaries = posts.map((post, index) => {
|
|
@@ -1999,9 +2014,7 @@ server.addTool({
|
|
|
1999
2014
|
timeFilter: args.time_filter,
|
|
2000
2015
|
limit: args.limit,
|
|
2001
2016
|
after: args.after
|
|
2002
|
-
})).fold((err) => {
|
|
2003
|
-
throw new Error(`Failed to get user comments: ${err.message}`);
|
|
2004
|
-
}, (page) => {
|
|
2017
|
+
})).fold((err) => toolError(`Failed to get user comments: ${err.message}`), (page) => {
|
|
2005
2018
|
const comments = page.items;
|
|
2006
2019
|
if (comments.length === 0) return `No comments found for u/${args.username} with the specified filters.`;
|
|
2007
2020
|
const commentSummaries = comments.map((comment, index) => {
|
|
@@ -2035,9 +2048,7 @@ server.addTool({
|
|
|
2035
2048
|
}),
|
|
2036
2049
|
execute: async (args) => {
|
|
2037
2050
|
const client = unwrapClient();
|
|
2038
|
-
return (await client.getPost(args.post_id, args.subreddit)).fold((err) => {
|
|
2039
|
-
throw new Error(`Failed to get post: ${err.message}`);
|
|
2040
|
-
}, (post) => {
|
|
2051
|
+
return (await client.getPost(args.post_id, args.subreddit)).fold((err) => toolError(`Failed to get post: ${err.message}`), (post) => {
|
|
2041
2052
|
const formattedPost = formatPostInfo(post);
|
|
2042
2053
|
return `# Post from r/${formattedPost.subreddit}
|
|
2043
2054
|
|
|
@@ -2090,9 +2101,7 @@ server.addTool({
|
|
|
2090
2101
|
after: z.string().optional().describe("Forward pagination cursor: the `after` value from a previous call. Omit for the first page.")
|
|
2091
2102
|
}),
|
|
2092
2103
|
execute: async (args) => {
|
|
2093
|
-
return (await unwrapClient().getTopPosts(args.subreddit ?? "", args.time_filter, args.limit, args.after)).fold((err) => {
|
|
2094
|
-
throw new Error(`Failed to get top posts: ${err.message}`);
|
|
2095
|
-
}, (page) => {
|
|
2104
|
+
return (await unwrapClient().getTopPosts(args.subreddit ?? "", args.time_filter, args.limit, args.after)).fold((err) => toolError(`Failed to get top posts: ${err.message}`), (page) => {
|
|
2096
2105
|
const posts = page.items;
|
|
2097
2106
|
if (posts.length === 0) return `No posts found in ${Option(args.subreddit).fold(() => "home feed", (sr) => `r/${sr}`)} for the specified time period.`;
|
|
2098
2107
|
const postSummaries = posts.map(formatPostInfo).map((post, index) => formatPostSummary(post, index, page.source)).join("\n\n");
|
|
@@ -2131,9 +2140,7 @@ server.addTool({
|
|
|
2131
2140
|
after: z.string().optional().describe("Forward pagination cursor: the `after` value from a previous call. Omit for the first page.")
|
|
2132
2141
|
}),
|
|
2133
2142
|
execute: async (args) => {
|
|
2134
|
-
return (await unwrapClient().browseSubreddit(args.subreddit ?? "", args.sort, args.time_filter, args.limit, args.after)).fold((err) => {
|
|
2135
|
-
throw new Error(`Failed to browse subreddit: ${err.message}`);
|
|
2136
|
-
}, (page) => {
|
|
2143
|
+
return (await unwrapClient().browseSubreddit(args.subreddit ?? "", args.sort, args.time_filter, args.limit, args.after)).fold((err) => toolError(`Failed to browse subreddit: ${err.message}`), (page) => {
|
|
2137
2144
|
const posts = page.items;
|
|
2138
2145
|
const location = Option(args.subreddit).fold(() => "home feed", (sr) => `r/${sr}`);
|
|
2139
2146
|
if (posts.length === 0) return `No posts found in ${location}.`;
|
|
@@ -2157,9 +2164,7 @@ server.addTool({
|
|
|
2157
2164
|
parameters: z.object({ subreddit_name: z.string().describe("The subreddit name, without the r/ prefix (e.g. 'askscience').") }),
|
|
2158
2165
|
execute: async (args) => {
|
|
2159
2166
|
const client = unwrapClient();
|
|
2160
|
-
return (await client.getSubredditInfo(args.subreddit_name)).fold((err) => {
|
|
2161
|
-
throw new Error(`Failed to get subreddit info: ${err.message}`);
|
|
2162
|
-
}, (subreddit) => {
|
|
2167
|
+
return (await client.getSubredditInfo(args.subreddit_name)).fold((err) => toolError(`Failed to get subreddit info: ${err.message}`), (subreddit) => {
|
|
2163
2168
|
const formattedSubreddit = formatSubredditInfo(subreddit);
|
|
2164
2169
|
return `# Subreddit Information: r/${formattedSubreddit.name}
|
|
2165
2170
|
|
|
@@ -2202,9 +2207,7 @@ server.addTool({
|
|
|
2202
2207
|
parameters: z.object({ subreddit_name: z.string().describe("The subreddit name, without the r/ prefix (e.g. 'AskReddit').") }),
|
|
2203
2208
|
execute: async (args) => {
|
|
2204
2209
|
const client = unwrapClient();
|
|
2205
|
-
return (await client.getSubredditRules(args.subreddit_name)).fold((err) => {
|
|
2206
|
-
throw new Error(`Failed to get subreddit rules: ${err.message}`);
|
|
2207
|
-
}, (rules) => {
|
|
2210
|
+
return (await client.getSubredditRules(args.subreddit_name)).fold((err) => toolError(`Failed to get subreddit rules: ${err.message}`), (rules) => {
|
|
2208
2211
|
if (rules.length === 0) return `r/${args.subreddit_name} has no listed subreddit-specific rules.`;
|
|
2209
2212
|
const ruleList = rules.map((rule, index) => {
|
|
2210
2213
|
const applies = rule.kind === "all" ? "posts & comments" : `${rule.kind}s`;
|
|
@@ -2227,9 +2230,7 @@ server.addTool({
|
|
|
2227
2230
|
},
|
|
2228
2231
|
parameters: z.object({ subreddit_name: z.string().describe("The subreddit name, without the r/ prefix (e.g. 'gadgets').") }),
|
|
2229
2232
|
execute: async (args) => {
|
|
2230
|
-
return (await unwrapClient().getPostFlairs(args.subreddit_name)).fold((err) => {
|
|
2231
|
-
throw new Error(`Failed to get post flairs: ${err.message}`);
|
|
2232
|
-
}, (flairs) => {
|
|
2233
|
+
return (await unwrapClient().getPostFlairs(args.subreddit_name)).fold((err) => toolError(`Failed to get post flairs: ${err.message}`), (flairs) => {
|
|
2233
2234
|
if (flairs.length === 0) return `r/${args.subreddit_name} has no selectable link flairs (or none are visible to this account).`;
|
|
2234
2235
|
const flairList = flairs.map((flair) => {
|
|
2235
2236
|
const editable = flair.textEditable === true ? " _(text editable)_" : "";
|
|
@@ -2253,9 +2254,7 @@ server.addTool({
|
|
|
2253
2254
|
},
|
|
2254
2255
|
parameters: z.object({}),
|
|
2255
2256
|
execute: async () => {
|
|
2256
|
-
return (await unwrapClient().getTrendingSubreddits()).fold((err) => {
|
|
2257
|
-
throw new Error(`Failed to get trending subreddits: ${err.message}`);
|
|
2258
|
-
}, (trendingSubreddits) => `# Trending Subreddits
|
|
2257
|
+
return (await unwrapClient().getTrendingSubreddits()).fold((err) => toolError(`Failed to get trending subreddits: ${err.message}`), (trendingSubreddits) => `# Trending Subreddits
|
|
2259
2258
|
|
|
2260
2259
|
${trendingSubreddits.map((subreddit, index) => `${index + 1}. r/${subreddit}`).join("\n")}`);
|
|
2261
2260
|
}
|
|
@@ -2296,7 +2295,7 @@ server.addTool({
|
|
|
2296
2295
|
}),
|
|
2297
2296
|
execute: async (args) => {
|
|
2298
2297
|
const client = unwrapClient();
|
|
2299
|
-
if (args.query.trim() === "")
|
|
2298
|
+
if (args.query.trim() === "") return toolError("Search query cannot be empty");
|
|
2300
2299
|
return (await client.searchReddit(args.query, {
|
|
2301
2300
|
subreddit: args.subreddit,
|
|
2302
2301
|
sort: args.sort,
|
|
@@ -2304,9 +2303,7 @@ server.addTool({
|
|
|
2304
2303
|
limit: args.limit,
|
|
2305
2304
|
type: args.type,
|
|
2306
2305
|
after: args.after
|
|
2307
|
-
})).fold((err) => {
|
|
2308
|
-
throw new Error(`Failed to search: ${err.message}`);
|
|
2309
|
-
}, (page) => {
|
|
2306
|
+
})).fold((err) => toolError(`Failed to search: ${err.message}`), (page) => {
|
|
2310
2307
|
const posts = page.items;
|
|
2311
2308
|
if (posts.length === 0) {
|
|
2312
2309
|
const searchLocation = Option(args.subreddit).fold(() => "", (sr) => ` in r/${sr}`);
|
|
@@ -2342,10 +2339,8 @@ server.addTool({
|
|
|
2342
2339
|
}),
|
|
2343
2340
|
execute: async (args) => {
|
|
2344
2341
|
const client = unwrapClient();
|
|
2345
|
-
if (
|
|
2346
|
-
return (await client.createPost(args.subreddit, args.title, args.content, args.is_self, args.flair_id, args.flair_text)).fold((err) => {
|
|
2347
|
-
throw new Error(`Failed to create post: ${err.message}`);
|
|
2348
|
-
}, (post) => {
|
|
2342
|
+
if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
|
|
2343
|
+
return (await client.createPost(args.subreddit, args.title, args.content, args.is_self, args.flair_id, args.flair_text)).fold((err) => toolError(`Failed to create post: ${err.message}`), (post) => {
|
|
2349
2344
|
const formattedPost = formatPostInfo(post);
|
|
2350
2345
|
return `# Post Created Successfully
|
|
2351
2346
|
|
|
@@ -2375,14 +2370,12 @@ server.addTool({
|
|
|
2375
2370
|
}),
|
|
2376
2371
|
execute: async (args) => {
|
|
2377
2372
|
const client = unwrapClient();
|
|
2378
|
-
if (
|
|
2379
|
-
return (await client.replyToPost(args.post_id, args.content)).fold((err) => {
|
|
2380
|
-
throw new Error(`Failed to reply: ${err.message}`);
|
|
2381
|
-
}, (comment) => `# Reply Posted Successfully
|
|
2373
|
+
if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
|
|
2374
|
+
return (await client.replyToPost(args.post_id, args.content)).fold((err) => toolError(`Failed to reply: ${err.message}`), (comment) => `# Reply Posted Successfully
|
|
2382
2375
|
|
|
2383
2376
|
## Comment Details
|
|
2384
2377
|
- Posted to: ${args.post_id}
|
|
2385
|
-
- Author: u/${
|
|
2378
|
+
- Author: u/${readEnv("REDDIT_USERNAME").orElse("")}
|
|
2386
2379
|
- Comment ID: ${comment.id}
|
|
2387
2380
|
|
|
2388
2381
|
Your reply has been successfully posted.`);
|
|
@@ -2401,10 +2394,8 @@ server.addTool({
|
|
|
2401
2394
|
parameters: z.object({ thing_id: z.string().describe("The post to delete: a full thing id 't3_<id>' or just the base36 post id '<id>' (the 't3_' prefix is added automatically). Must be a post you authored.") }),
|
|
2402
2395
|
execute: async (args) => {
|
|
2403
2396
|
const client = unwrapClient();
|
|
2404
|
-
if (
|
|
2405
|
-
return (await client.deletePost(args.thing_id)).fold((err) => {
|
|
2406
|
-
throw new Error(`Failed to delete post: ${err.message}`);
|
|
2407
|
-
}, () => `# Post Deleted Successfully
|
|
2397
|
+
if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
|
|
2398
|
+
return (await client.deletePost(args.thing_id)).fold((err) => toolError(`Failed to delete post: ${err.message}`), () => `# Post Deleted Successfully
|
|
2408
2399
|
|
|
2409
2400
|
The post ${args.thing_id} has been permanently deleted from Reddit.
|
|
2410
2401
|
|
|
@@ -2424,10 +2415,8 @@ server.addTool({
|
|
|
2424
2415
|
parameters: z.object({ thing_id: z.string().describe("The comment to delete: a full thing id 't1_<id>' or just the base36 comment id '<id>' (the 't1_' prefix is added automatically). Must be a comment you authored.") }),
|
|
2425
2416
|
execute: async (args) => {
|
|
2426
2417
|
const client = unwrapClient();
|
|
2427
|
-
if (
|
|
2428
|
-
return (await client.deleteComment(args.thing_id)).fold((err) => {
|
|
2429
|
-
throw new Error(`Failed to delete comment: ${err.message}`);
|
|
2430
|
-
}, () => `# Comment Deleted Successfully
|
|
2418
|
+
if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
|
|
2419
|
+
return (await client.deleteComment(args.thing_id)).fold((err) => toolError(`Failed to delete comment: ${err.message}`), () => `# Comment Deleted Successfully
|
|
2431
2420
|
|
|
2432
2421
|
The comment ${args.thing_id} has been permanently deleted from Reddit.
|
|
2433
2422
|
|
|
@@ -2450,10 +2439,8 @@ server.addTool({
|
|
|
2450
2439
|
}),
|
|
2451
2440
|
execute: async (args) => {
|
|
2452
2441
|
const client = unwrapClient();
|
|
2453
|
-
if (
|
|
2454
|
-
return (await client.editPost(args.thing_id, args.new_text)).fold((err) => {
|
|
2455
|
-
throw new Error(`Failed to edit post: ${err.message}`);
|
|
2456
|
-
}, () => `# Post Edited Successfully
|
|
2442
|
+
if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
|
|
2443
|
+
return (await client.editPost(args.thing_id, args.new_text)).fold((err) => toolError(`Failed to edit post: ${err.message}`), () => `# Post Edited Successfully
|
|
2457
2444
|
|
|
2458
2445
|
The post ${args.thing_id} has been updated with your new content.
|
|
2459
2446
|
|
|
@@ -2480,10 +2467,8 @@ server.addTool({
|
|
|
2480
2467
|
}),
|
|
2481
2468
|
execute: async (args) => {
|
|
2482
2469
|
const client = unwrapClient();
|
|
2483
|
-
if (
|
|
2484
|
-
return (await client.editComment(args.thing_id, args.new_text)).fold((err) => {
|
|
2485
|
-
throw new Error(`Failed to edit comment: ${err.message}`);
|
|
2486
|
-
}, () => `# Comment Edited Successfully
|
|
2470
|
+
if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
|
|
2471
|
+
return (await client.editComment(args.thing_id, args.new_text)).fold((err) => toolError(`Failed to edit comment: ${err.message}`), () => `# Comment Edited Successfully
|
|
2487
2472
|
|
|
2488
2473
|
The comment ${args.thing_id} has been updated with your new content.
|
|
2489
2474
|
|
|
@@ -2506,10 +2491,8 @@ server.addTool({
|
|
|
2506
2491
|
}),
|
|
2507
2492
|
execute: async (args) => {
|
|
2508
2493
|
const client = unwrapClient();
|
|
2509
|
-
if (
|
|
2510
|
-
return (await client.saveContent(args.thing_id, args.category)).fold((err) => {
|
|
2511
|
-
throw new Error(`Failed to save content: ${err.message}`);
|
|
2512
|
-
}, () => `# Content Saved Successfully
|
|
2494
|
+
if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
|
|
2495
|
+
return (await client.saveContent(args.thing_id, args.category)).fold((err) => toolError(`Failed to save content: ${err.message}`), () => `# Content Saved Successfully
|
|
2513
2496
|
|
|
2514
2497
|
${args.thing_id} has been saved to your account. Use get_my_saved to view your saved items.`);
|
|
2515
2498
|
}
|
|
@@ -2527,10 +2510,8 @@ server.addTool({
|
|
|
2527
2510
|
parameters: z.object({ thing_id: z.string().describe("The post or comment to unsave: a full thing id 't3_<id>' (post) or 't1_<id>' (comment). A bare id is treated as a post.") }),
|
|
2528
2511
|
execute: async (args) => {
|
|
2529
2512
|
const client = unwrapClient();
|
|
2530
|
-
if (
|
|
2531
|
-
return (await client.unsaveContent(args.thing_id)).fold((err) => {
|
|
2532
|
-
throw new Error(`Failed to unsave content: ${err.message}`);
|
|
2533
|
-
}, () => `# Content Unsaved Successfully
|
|
2513
|
+
if (!hasUserCredentials()) return toolError("User authentication required. Please set REDDIT_USERNAME and REDDIT_PASSWORD environment variables.");
|
|
2514
|
+
return (await client.unsaveContent(args.thing_id)).fold((err) => toolError(`Failed to unsave content: ${err.message}`), () => `# Content Unsaved Successfully
|
|
2534
2515
|
|
|
2535
2516
|
${args.thing_id} has been removed from your saved items.`);
|
|
2536
2517
|
}
|
|
@@ -2558,13 +2539,11 @@ server.addTool({
|
|
|
2558
2539
|
}),
|
|
2559
2540
|
execute: async (args) => {
|
|
2560
2541
|
const client = unwrapClient();
|
|
2561
|
-
if (args.post_id === "" || args.subreddit === "")
|
|
2542
|
+
if (args.post_id === "" || args.subreddit === "") return toolError("post_id and subreddit are required");
|
|
2562
2543
|
return (await client.getPostComments(args.post_id, args.subreddit, {
|
|
2563
2544
|
sort: args.sort,
|
|
2564
2545
|
limit: args.limit
|
|
2565
|
-
})).fold((err) => {
|
|
2566
|
-
throw new Error(`Failed to get comments: ${err.message}`);
|
|
2567
|
-
}, ({ post, comments, moreIds }) => {
|
|
2546
|
+
})).fold((err) => toolError(`Failed to get comments: ${err.message}`), ({ post, comments, moreIds }) => {
|
|
2568
2547
|
const statsLine = client.keyless ? "" : `- Score: ${post.score.toLocaleString()} | Comments: ${post.numComments.toLocaleString()}\n`;
|
|
2569
2548
|
const header = `# Comments for: ${post.title}
|
|
2570
2549
|
|
|
@@ -2605,9 +2584,7 @@ server.addTool({
|
|
|
2605
2584
|
}),
|
|
2606
2585
|
execute: async (args) => {
|
|
2607
2586
|
const client = unwrapClient();
|
|
2608
|
-
return (await client.getMoreComments(args.link_id, args.comment_ids)).fold((err) => {
|
|
2609
|
-
throw new Error(`Failed to expand comments: ${err.message}`);
|
|
2610
|
-
}, (comments) => {
|
|
2587
|
+
return (await client.getMoreComments(args.link_id, args.comment_ids)).fold((err) => toolError(`Failed to expand comments: ${err.message}`), (comments) => {
|
|
2611
2588
|
if (comments.length === 0) return "No additional comments were returned for those ids.";
|
|
2612
2589
|
const commentList = comments.map((comment, index) => {
|
|
2613
2590
|
const formatted = formatCommentInfo(comment, 300);
|
|
@@ -2626,9 +2603,8 @@ ${commentList}${archiveDisclaimer(client)}`;
|
|
|
2626
2603
|
});
|
|
2627
2604
|
async function main() {
|
|
2628
2605
|
await setupRedditClient();
|
|
2629
|
-
const
|
|
2630
|
-
const
|
|
2631
|
-
const host = process.env.HOST ?? "127.0.0.1";
|
|
2606
|
+
const port = parseInt(readEnv("PORT").orElse("3000"));
|
|
2607
|
+
const host = readEnv("HOST").orElse("127.0.0.1");
|
|
2632
2608
|
if (useHttp) {
|
|
2633
2609
|
console.error(`[Setup] Starting HTTP server on ${host}:${port}`);
|
|
2634
2610
|
await server.start({
|
|
@@ -2636,11 +2612,11 @@ async function main() {
|
|
|
2636
2612
|
httpStream: {
|
|
2637
2613
|
port,
|
|
2638
2614
|
host,
|
|
2639
|
-
endpoint: "/mcp"
|
|
2615
|
+
endpoint: "/mcp",
|
|
2616
|
+
cors: true
|
|
2640
2617
|
}
|
|
2641
2618
|
});
|
|
2642
2619
|
console.error(`[Setup] HTTP server ready at http://${host}:${port}/mcp`);
|
|
2643
|
-
console.error(`[Setup] SSE endpoint available at http://${host}:${port}/sse`);
|
|
2644
2620
|
} else {
|
|
2645
2621
|
console.error("[Setup] Starting in stdio mode");
|
|
2646
2622
|
if (process.stdin.isTTY) {
|