-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathserver.py
More file actions
2327 lines (2035 loc) · 95.8 KB
/
server.py
File metadata and controls
2327 lines (2035 loc) · 95.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functools
import logging
import time
from datetime import datetime
from os import getenv
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, TypeVar, cast
import praw # type: ignore
from mcp.server.fastmcp import FastMCP
F = TypeVar("F", bound=Callable[..., Any])
if TYPE_CHECKING:
pass
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class RedditClientManager:
"""Manages the Reddit client and its state."""
_instance = None
_client = None
_is_read_only = True
def __new__(cls) -> "RedditClientManager":
if cls._instance is None:
cls._instance = super(RedditClientManager, cls).__new__(cls)
cls._instance._initialize_client()
return cls._instance
def _initialize_client(self) -> None:
"""Initialize the Reddit client with appropriate credentials."""
client_id = getenv("REDDIT_CLIENT_ID")
client_secret = getenv("REDDIT_CLIENT_SECRET")
user_agent = getenv("REDDIT_USER_AGENT", "RedditMCPServer v1.0")
username = getenv("REDDIT_USERNAME")
password = getenv("REDDIT_PASSWORD")
self._is_read_only = True
try:
# Try authenticated access first if credentials are provided
if all([username, password, client_id, client_secret]):
logger.info(
f"Attempting to initialize Reddit client with user authentication for u/{username}"
)
try:
self._client = praw.Reddit(
client_id=client_id,
client_secret=client_secret,
user_agent=user_agent,
username=username,
password=password,
check_for_updates=False,
)
# Test authentication
if self._client.user.me() is None:
raise ValueError(f"Failed to authenticate as u/{username}")
logger.info(f"Successfully authenticated as u/{username}")
self._is_read_only = False
return
except Exception as auth_error:
logger.warning(f"Authentication failed: {auth_error}")
logger.info("Falling back to read-only access")
# Fall back to read-only with client credentials
if client_id and client_secret:
logger.info("Initializing Reddit client with read-only access")
self._client = praw.Reddit(
client_id=client_id,
client_secret=client_secret,
user_agent=user_agent,
check_for_updates=False,
read_only=True,
)
return
# Last resort: read-only without credentials
logger.info(
"Initializing Reddit client in read-only mode without credentials"
)
self._client = praw.Reddit(
user_agent=user_agent,
check_for_updates=False,
read_only=True,
)
# Test read-only access
self._client.subreddit("popular").hot(limit=1)
except Exception as e:
logger.error(f"Error initializing Reddit client: {e}")
self._client = None
@property
def client(self) -> Optional[praw.Reddit]:
"""Get the Reddit client instance."""
return self._client
@property
def is_read_only(self) -> bool:
"""Check if the client is in read-only mode."""
return self._is_read_only
def check_user_auth(self) -> bool:
"""Check if user authentication is available for write operations."""
if not self._client:
logger.error("Reddit client not initialized")
return False
if self._is_read_only:
logger.error("Reddit client is in read-only mode")
return False
return True
def require_write_access(func: F) -> F:
"""Decorator to ensure write access is available."""
@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
reddit_manager = RedditClientManager()
if reddit_manager.is_read_only:
raise ValueError(
"Write operation not allowed in read-only mode. Please provide valid credentials."
)
if not reddit_manager.check_user_auth():
raise Exception(
"Authentication required for write operations. "
"Please provide valid REDDIT_USERNAME and REDDIT_PASSWORD environment variables."
)
return func(*args, **kwargs)
return cast(F, wrapper)
mcp = FastMCP("Reddit MCP")
reddit_manager = RedditClientManager()
def _format_timestamp(timestamp: float) -> str:
"""Convert Unix timestamp to human readable format.
Args:
timestamp (float): Unix timestamp
Returns:
str: Formatted date string
"""
try:
dt = datetime.fromtimestamp(timestamp)
return dt.strftime("%Y-%m-%d %H:%M:%S UTC")
except Exception:
return str(timestamp)
def _analyze_post_engagement(score: int, ratio: float, num_comments: int) -> str:
"""Generate insights about post engagement and performance."""
insights = []
# Analyze score and ratio
if score > 1000 and ratio > 0.95:
insights.append("Highly successful post with strong community approval")
elif score > 100 and ratio > 0.8:
insights.append("Well-received post with good engagement")
elif ratio < 0.5:
insights.append("Controversial post that sparked debate")
# Analyze comment activity
if num_comments > 100:
insights.append("Generated significant discussion")
elif num_comments > score * 0.5:
insights.append("Highly discussable content with active comment section")
elif num_comments == 0:
insights.append("Yet to receive community interaction")
return "\n - ".join(insights)
def _format_post(post: praw.models.Submission) -> str:
"""Format post information with AI-driven insights."""
content_type = "Text Post" if post.is_self else "Link Post"
content = post.selftext if post.is_self else post.url
flags = []
if post.over_18:
flags.append("NSFW")
if hasattr(post, "spoiler") and post.spoiler:
flags.append("Spoiler")
if post.edited:
flags.append("Edited")
# Add image URL section for non-self posts
image_url_section = (
f"""
• Image URL: {post.url}"""
if not post.is_self
else ""
)
return f"""
• Title: {post.title}
• Type: {content_type}
• Content: {content}
• Author: u/{str(post.author)}
• Subreddit: r/{str(post.subreddit)}{image_url_section}
• Stats:
- Score: {post.score:,}
- Upvote Ratio: {post.upvote_ratio * 100:.1f}%
- Comments: {post.num_comments:,}
• Metadata:
- Posted: {_format_timestamp(post.created_utc)}
- Flags: {", ".join(flags) if flags else "None"}
- Flair: {post.link_flair_text or "None"}
• Links:
- Full Post: https://reddit.com{post.permalink}
- Short Link: https://redd.it/{post.id}
📈 Engagement Analysis:
- {_analyze_post_engagement(post.score, post.upvote_ratio, post.num_comments)}
🎯 Best Time to Engage:
- {_get_best_engagement_time(post.created_utc, post.score)}
"""
def _get_best_engagement_time(created_utc: float, score: int) -> str:
"""Analyze and suggest optimal posting times based on post performance."""
post_hour = datetime.fromtimestamp(created_utc).hour
# Simple time zone analysis
if 14 <= post_hour <= 18: # Peak Reddit hours
return "Posted during peak engagement hours (2 PM - 6 PM), good timing!"
elif 23 <= post_hour or post_hour <= 5:
return "Consider posting during more active hours (morning to evening)"
else:
return "Posted during moderate activity hours, timing could be optimized"
def _extract_reddit_id(reddit_id: str) -> str:
"""Extract the base ID from a Reddit URL or ID.
Args:
reddit_id: Either a Reddit ID or a URL containing the ID
Returns:
The extracted Reddit ID
"""
if not reddit_id:
raise ValueError("Empty ID provided")
# If it's a URL, extract the ID part
if "/" in reddit_id:
# Handle both standard URLs and permalinks
parts = [p for p in reddit_id.split("/") if p]
# The ID is typically the last non-empty part
reddit_id = parts[-1]
logger.debug(f"Extracted ID {reddit_id} from URL")
return reddit_id
def _format_comment(comment: praw.models.Comment) -> str:
"""Format comment information with AI-driven insights."""
flags = []
if comment.edited:
flags.append("Edited")
if hasattr(comment, "is_submitter") and comment.is_submitter:
flags.append("OP")
return f"""
• Author: u/{str(comment.author)}
• Content: {comment.body}
• Stats:
- Score: {comment.score:,}
- Controversiality: {comment.controversiality if hasattr(comment, "controversiality") else "Unknown"}
• Context:
- Subreddit: r/{str(comment.subreddit)}
- Thread: {comment.submission.title}
• Metadata:
- Posted: {_format_timestamp(comment.created_utc)}
- Flags: {", ".join(flags) if flags else "None"}
• Link: https://reddit.com{comment.permalink}
💬 Comment Analysis:
- {_analyze_comment_impact(comment.score, bool(comment.edited), hasattr(comment, "is_submitter"))}
"""
def _analyze_comment_impact(score: int, is_edited: bool, is_op: bool) -> str:
"""Analyze comment's impact and context."""
insights = []
if score > 100:
insights.append("Highly upvoted comment with significant community agreement")
elif score < 0:
insights.append("Controversial or contested viewpoint")
if is_edited:
insights.append("Refined for clarity or accuracy")
if is_op:
insights.append("Author's perspective adds context to original post")
return "\n - ".join(insights or ["Standard engagement with discussion"])
def _serialize_comment_tree(comment: praw.models.Comment) -> Dict[str, Any]:
"""Serialize a PRAW comment into a JSON-serializable tree structure."""
try:
replies = []
if getattr(comment, "replies", None):
replies = [
_serialize_comment_tree(reply)
for reply in comment.replies
if isinstance(reply, praw.models.Comment)
]
except Exception as e:
logger.error(f"Error while serializing replies for comment {getattr(comment, 'id', 'unknown')}: {e}")
replies = []
return {
"id": comment.id,
"author": str(comment.author) if comment.author else "[deleted]",
"body": getattr(comment, "body", ""),
"score": getattr(comment, "score", 0),
"created_utc": getattr(comment, "created_utc", 0.0),
"permalink": getattr(comment, "permalink", ""),
"is_submitter": getattr(comment, "is_submitter", False),
"distinguished": getattr(comment, "distinguished", None),
"stickied": getattr(comment, "stickied", False),
"locked": getattr(comment, "locked", False),
"replies": replies,
}
@mcp.tool()
def get_user_info(username: str) -> Dict[str, Any]:
"""Get information about a Reddit user.
Args:
username: The username of the Reddit user to get info for
Returns:
Dictionary containing user information with the following structure:
{
'username': str, # User's username
'created_utc': float, # Account creation timestamp
'comment_karma': int, # User's comment karma
'link_karma': int, # User's post/link karma
'has_verified_email': bool, # Whether email is verified
'is_mod': bool, # Whether user is a moderator
'is_gold': bool, # Whether user has Reddit premium
'has_subscribed': bool, # Whether user has subscribed to premium
'is_employee': bool, # Whether user is a Reddit employee
'over_18': bool, # Whether user is marked as NSFW
'is_suspended': bool, # Whether account is suspended
'suspension_expiration_utc': Optional[float], # When suspension ends if suspended
'total_karma': int, # Total karma (comments + posts)
'subreddit': Optional[Dict], # User's profile subreddit info if exists
}
Raises:
ValueError: If the username is invalid or not found
RuntimeError: For other errors during the operation
"""
manager = RedditClientManager()
if not manager.client:
raise RuntimeError("Reddit client not initialized")
if not username or not isinstance(username, str) or username.startswith((" ", "/")):
raise ValueError("Invalid username provided")
# Clean up the username (remove u/ prefix if present)
clean_username = username[2:] if username.startswith("u/") else username
try:
logger.info(f"Getting info for u/{clean_username}")
user = manager.client.redditor(clean_username)
# Force fetch user data to verify it exists
_ = user.created_utc
# Format the user info in a structured way
return {
"username": user.name,
"created_utc": user.created_utc,
"comment_karma": user.comment_karma,
"link_karma": user.link_karma,
"has_verified_email": getattr(user, "has_verified_email", False),
"is_mod": getattr(user, "is_mod", False),
"is_gold": getattr(user, "is_gold", False),
"has_subscribed": getattr(user, "has_subscribed", False),
"is_employee": getattr(user, "is_employee", False),
"over_18": getattr(user, "over_18", False),
"is_suspended": getattr(user, "is_suspended", False),
"suspension_expiration_utc": getattr(
user, "suspension_expiration_utc", None
),
"total_karma": getattr(
user, "total_karma", user.comment_karma + user.link_karma
),
"subreddit": {
"display_name": user.subreddit.display_name,
"title": getattr(user.subreddit, "title", ""),
"public_description": getattr(user.subreddit, "public_description", ""),
"subscribers": getattr(user.subreddit, "subscribers", 0),
}
if hasattr(user, "subreddit") and user.subreddit
else None,
}
except Exception as e:
logger.error(f"Error getting user info for u/{clean_username}: {e}")
if hasattr(e, "message") and "USER_DOESNT_EXIST" in str(e):
raise ValueError(f"User u/{clean_username} not found") from e
if "NOT_FOUND" in str(e):
raise ValueError(f"User u/{clean_username} not found") from e
raise RuntimeError(f"Failed to get user info: {e}") from e
@mcp.tool()
def get_user_comments(
username: str,
sort: str = "new",
time_filter: str = "all",
limit: int = 25,
) -> Dict[str, Any]:
"""Get a user's comment history.
Args:
username: The username of the Reddit user (with or without 'u/' prefix)
sort: Sort order for comments - one of: "new", "hot", "top", "controversial"
time_filter: Time period to filter comments (e.g. "hour", "day", "week", "month", "year", "all")
limit: Number of comments to return (1-100)
Returns:
Dictionary containing structured comment history with the following structure:
{
'username': str, # The username
'sort': str, # Sort method used
'time_filter': str, # Time filter used
'comments': [ # List of comments
{
'id': str, # Comment ID
'body': str, # Comment text content
'author': str, # Author's username
'subreddit': str, # Subreddit where comment was posted
'score': int, # Comment score (upvotes - downvotes)
'created_utc': float, # Comment creation timestamp
'permalink': str, # Relative URL to the comment
'link_title': str, # Title of the post being commented on
'link_id': str, # ID of the post
'parent_id': str, # ID of parent comment or post
'is_submitter': bool, # Whether commenter is the post author
'stickied': bool, # Whether comment is stickied
'distinguished': Optional[str], # Distinguishing type (e.g., 'moderator')
'edited': bool, # Whether comment has been edited
'gilded': int, # Number of times gilded
'controversiality': int, # Controversy score
'depth': int, # Comment depth in thread (0 for top-level)
},
...
],
'metadata': {
'fetched_at': float, # Timestamp when data was fetched
'comment_count': int, # Number of comments returned
}
}
Raises:
ValueError: If username is invalid, sort method is invalid, or time_filter is invalid
RuntimeError: For other errors during the operation
"""
manager = RedditClientManager()
if not manager.client:
raise RuntimeError("Reddit client not initialized")
# Validate username
if not username or not isinstance(username, str) or username.startswith((" ", "/")):
raise ValueError("Invalid username provided")
# Clean username
clean_username = username[2:] if username.startswith("u/") else username
# Validate sort method
valid_sort = ["new", "hot", "top", "controversial"]
if sort not in valid_sort:
raise ValueError(
f"Invalid sort method: {sort}. Must be one of: {', '.join(valid_sort)}"
)
# Validate time_filter
valid_time_filters = ["hour", "day", "week", "month", "year", "all"]
if time_filter not in valid_time_filters:
raise ValueError(
f"Invalid time_filter: {time_filter}. Must be one of: {', '.join(valid_time_filters)}"
)
# Clamp limit to valid range
limit = max(1, min(100, limit))
try:
logger.info(
f"Getting {limit} {sort} comments for u/{clean_username} (time_filter={time_filter})"
)
user = manager.client.redditor(clean_username)
# Get comments based on sort method
if sort == "new":
comments = user.comments.new(limit=limit)
elif sort == "hot":
comments = user.comments.hot(limit=limit)
elif sort == "top":
comments = user.comments.top(time_filter=time_filter, limit=limit)
elif sort == "controversial":
comments = user.comments.controversial(time_filter=time_filter, limit=limit)
# Convert to list and format
comments_list = list(comments)
formatted_comments = []
for comment in comments_list:
comment_data = {
"id": comment.id,
"body": comment.body,
"author": comment.author.name if comment.author else "[deleted]",
"subreddit": comment.subreddit.display_name,
"score": comment.score,
"created_utc": comment.created_utc,
"permalink": comment.permalink,
"link_title": getattr(comment, "link_title", ""),
"link_id": comment.link_id,
"parent_id": comment.parent_id,
"is_submitter": comment.is_submitter,
"stickied": comment.stickied,
"distinguished": comment.distinguished,
"edited": bool(comment.edited),
"gilded": getattr(comment, "gilded", 0),
"controversiality": getattr(comment, "controversiality", 0),
"depth": getattr(comment, "depth", 0),
}
formatted_comments.append(comment_data)
return {
"username": clean_username,
"sort": sort,
"time_filter": time_filter,
"comments": formatted_comments,
"metadata": {
"fetched_at": time.time(),
"comment_count": len(formatted_comments),
},
}
except Exception as e:
logger.error(f"Error getting comments for u/{clean_username}: {e}")
if "NOT_FOUND" in str(e) or "USER_DOESNT_EXIST" in str(e):
raise ValueError(f"User u/{clean_username} not found") from e
raise RuntimeError(f"Failed to get user comments: {e}") from e
@mcp.tool()
def get_user_posts(
username: str,
sort: str = "new",
time_filter: str = "all",
limit: int = 25,
) -> Dict[str, Any]:
"""Get a user's post/submission history.
Args:
username: The username of the Reddit user (with or without 'u/' prefix)
sort: Sort order for posts - one of: "new", "hot", "top", "controversial"
time_filter: Time period to filter posts (e.g. "hour", "day", "week", "month", "year", "all")
limit: Number of posts to return (1-100)
Returns:
Dictionary containing structured post history with the following structure:
{
'username': str, # The username
'sort': str, # Sort method used
'time_filter': str, # Time filter used
'posts': [ # List of posts
{
'id': str, # Post ID
'title': str, # Post title
'author': str, # Author's username
'subreddit': str, # Subreddit name
'score': int, # Post score (upvotes - downvotes)
'upvote_ratio': float, # Ratio of upvotes to total votes
'num_comments': int, # Number of comments
'created_utc': float, # Post creation timestamp
'url': str, # Full URL to the post
'permalink': str, # Relative URL to the post
'is_self': bool, # Whether it's a self (text) post
'selftext': str, # Content of self post (if any)
'link_url': str, # URL for link posts (if any)
'domain': str, # Domain of the linked content
'over_18': bool, # Whether marked as NSFW
'spoiler': bool, # Whether marked as spoiler
'stickied': bool, # Whether stickied in the subreddit
'locked': bool, # Whether comments are locked
'distinguished': Optional[str], # Distinguishing type (e.g., 'moderator')
'gilded': int, # Number of times gilded
},
...
],
'metadata': {
'fetched_at': float, # Timestamp when data was fetched
'post_count': int, # Number of posts returned
}
}
Raises:
ValueError: If username is invalid, sort method is invalid, or time_filter is invalid
RuntimeError: For other errors during the operation
"""
manager = RedditClientManager()
if not manager.client:
raise RuntimeError("Reddit client not initialized")
# Validate username
if not username or not isinstance(username, str) or username.startswith((" ", "/")):
raise ValueError("Invalid username provided")
# Clean username
clean_username = username[2:] if username.startswith("u/") else username
# Validate sort method
valid_sort = ["new", "hot", "top", "controversial"]
if sort not in valid_sort:
raise ValueError(
f"Invalid sort method: {sort}. Must be one of: {', '.join(valid_sort)}"
)
# Validate time_filter
valid_time_filters = ["hour", "day", "week", "month", "year", "all"]
if time_filter not in valid_time_filters:
raise ValueError(
f"Invalid time_filter: {time_filter}. Must be one of: {', '.join(valid_time_filters)}"
)
# Clamp limit to valid range
limit = max(1, min(100, limit))
try:
logger.info(
f"Getting {limit} {sort} posts for u/{clean_username} (time_filter={time_filter})"
)
user = manager.client.redditor(clean_username)
# Get posts based on sort method
if sort == "new":
posts = user.submissions.new(limit=limit)
elif sort == "hot":
posts = user.submissions.hot(limit=limit)
elif sort == "top":
posts = user.submissions.top(time_filter=time_filter, limit=limit)
elif sort == "controversial":
posts = user.submissions.controversial(time_filter=time_filter, limit=limit)
# Convert to list and format
posts_list = list(posts)
formatted_posts = []
for post in posts_list:
post_data = {
"id": post.id,
"title": post.title,
"author": post.author.name if post.author else "[deleted]",
"subreddit": post.subreddit.display_name,
"score": post.score,
"upvote_ratio": post.upvote_ratio,
"num_comments": post.num_comments,
"created_utc": post.created_utc,
"url": f"https://reddit.com{post.permalink}",
"permalink": post.permalink,
"is_self": post.is_self,
"selftext": post.selftext if post.is_self else "",
"link_url": post.url if not post.is_self else "",
"domain": post.domain,
"over_18": post.over_18,
"spoiler": post.spoiler,
"stickied": post.stickied,
"locked": post.locked,
"distinguished": post.distinguished,
"gilded": getattr(post, "gilded", 0),
}
formatted_posts.append(post_data)
return {
"username": clean_username,
"sort": sort,
"time_filter": time_filter,
"posts": formatted_posts,
"metadata": {
"fetched_at": time.time(),
"post_count": len(formatted_posts),
},
}
except Exception as e:
logger.error(f"Error getting posts for u/{clean_username}: {e}")
if "NOT_FOUND" in str(e) or "USER_DOESNT_EXIST" in str(e):
raise ValueError(f"User u/{clean_username} not found") from e
raise RuntimeError(f"Failed to get user posts: {e}") from e
@mcp.tool()
def get_top_posts(
subreddit: str,
time_filter: str = "week",
limit: int = 10,
include_comments: bool = False,
comment_replace_more_limit: int = 0,
) -> Dict[str, Any]:
"""Get top posts from a subreddit.
Args:
subreddit: Name of the subreddit (with or without 'r/' prefix)
time_filter: Time period to filter posts (e.g. "day", "week", "month", "year", "all")
limit: Number of posts to fetch (1-100)
include_comments: If True, load and return the full comment forest for each post
comment_replace_more_limit: Limit for replacing "MoreComments" objects (0 for none, None for all)
Returns:
Dictionary containing structured post information with the following structure:
{
'subreddit': str, # Subreddit name
'time_filter': str, # The time period used for filtering
'posts': [ # List of posts, each with the following structure:
{
'id': str, # Post ID
'title': str, # Post title
'author': str, # Author's username
'score': int, # Post score (upvotes - downvotes)
'upvote_ratio': float, # Ratio of upvotes to total votes
'num_comments': int, # Number of comments
'created_utc': float, # Post creation timestamp
'url': str, # URL to the post
'permalink': str, # Relative URL to the post
'is_self': bool, # Whether it's a self (text) post
'selftext': str, # Content of self post (if any)
'link_url': str, # URL for link posts (if any)
'over_18': bool, # Whether marked as NSFW
'spoiler': bool, # Whether marked as spoiler
'stickied': bool, # Whether stickied in the subreddit
'locked': bool, # Whether comments are locked
'distinguished': Optional[str], # Distinguishing type (e.g., 'moderator')
'flair': Optional[Dict], # Post flair information if any
'comments': Optional[List[Dict]], # present if include_comments is True
},
...
],
'metadata': {
'fetched_at': float, # Timestamp when data was fetched
'post_count': int, # Number of posts returned
}
}
Raises:
ValueError: If subreddit is invalid or time_filter is not valid
RuntimeError: For other errors during the operation
"""
manager = RedditClientManager()
if not manager.client:
raise RuntimeError("Reddit client not initialized")
if not subreddit or not isinstance(subreddit, str):
raise ValueError("Subreddit name is required")
valid_time_filters = ["hour", "day", "week", "month", "year", "all"]
if time_filter not in valid_time_filters:
raise ValueError(
f"Invalid time filter. Must be one of: {', '.join(valid_time_filters)}"
)
limit = max(1, min(100, limit)) # Ensure limit is between 1 and 100
# Clean up subreddit name (remove r/ prefix if present)
clean_subreddit = subreddit[2:] if subreddit.startswith("r/") else subreddit
try:
logger.info(
f"Getting top {limit} posts from r/{clean_subreddit} "
f"(time_filter={time_filter}, include_comments={include_comments})"
)
# Get the subreddit
sub = manager.client.subreddit(clean_subreddit)
# Verify subreddit exists and is accessible
_ = sub.display_name
# Fetch posts
posts = list(sub.top(time_filter=time_filter, limit=limit))
if not posts:
return {
"subreddit": clean_subreddit,
"time_filter": time_filter,
"posts": [],
"metadata": {"fetched_at": time.time(), "post_count": 0},
}
# Format posts into structured data
formatted_posts = []
for post in posts:
try:
# Get post data with error handling for each field
post_data: Dict[str, Any] = {
"id": post.id,
"title": post.title,
"author": str(post.author) if getattr(post, "author", None) else "[deleted]",
"score": getattr(post, "score", 0),
"upvote_ratio": getattr(post, "upvote_ratio", 0.0),
"num_comments": getattr(post, "num_comments", 0),
"created_utc": post.created_utc,
"url": f"https://www.reddit.com{post.permalink}" if hasattr(post, "permalink") else "",
"permalink": getattr(post, "permalink", ""),
"is_self": getattr(post, "is_self", False),
"selftext": getattr(post, "selftext", ""),
"link_url": getattr(post, "url", ""),
"over_18": getattr(post, "over_18", False),
"spoiler": getattr(post, "spoiler", False),
"stickied": getattr(post, "stickied", False),
"locked": getattr(post, "locked", False),
"distinguished": getattr(post, "distinguished", None),
}
# Add flair information if available
if hasattr(post, "link_flair_text") and post.link_flair_text:
post_data["flair"] = {
"text": post.link_flair_text,
"css_class": getattr(post, "link_flair_css_class", ""),
"template_id": getattr(post, "link_flair_template_id", None),
"text_color": getattr(post, "link_flair_text_color", None),
"background_color": getattr(
post, "link_flair_background_color", None
),
}
else:
post_data["flair"] = None
# Add comments if requested
if include_comments:
try:
# Resolve all MoreComments to get the complete tree
# limit=0 removes no MoreComments, limit=None removes all (slow!)
post.comments.replace_more(limit=comment_replace_more_limit)
top_level_comments = [
c
for c in post.comments
if isinstance(c, praw.models.Comment)
]
post_data["comments"] = [
_serialize_comment_tree(c) for c in top_level_comments
]
except Exception as comments_error:
logger.exception(
f"Error loading comments for post {getattr(post, 'id', 'unknown')}"
)
post_data["comments"] = []
formatted_posts.append(post_data)
except Exception as post_error:
logger.error(
f"Error processing post {getattr(post, 'id', 'unknown')}: {post_error}"
)
continue
return {
"subreddit": clean_subreddit,
"time_filter": time_filter,
"posts": formatted_posts,
"metadata": {
"fetched_at": time.time(),
"post_count": len(formatted_posts),
},
}
except Exception as e:
logger.error(f"Error getting top posts from r/{clean_subreddit}: {e}")
if "private" in str(e).lower():
raise ValueError(
f"r/{clean_subreddit} is private or cannot be accessed"
) from e
if "banned" in str(e).lower():
raise ValueError(
f"r/{clean_subreddit} has been banned or doesn't exist"
) from e
if "not found" in str(e).lower():
raise ValueError(f"r/{clean_subreddit} not found") from e
raise RuntimeError(f"Failed to get top posts: {e}") from e
@mcp.tool()
def get_subreddit_info(subreddit_name: str) -> Dict[str, Any]:
"""Get information about a subreddit.
Args:
subreddit_name: Name of the subreddit (with or without 'r/' prefix)
Returns:
Dictionary containing subreddit information
Raises:
ValueError: If subreddit_name is invalid or subreddit not found
RuntimeError: For other errors during the operation
"""
manager = RedditClientManager()
if not manager.client:
raise RuntimeError("Reddit client not initialized")
if not subreddit_name or not isinstance(subreddit_name, str):
raise ValueError("Subreddit name is required")
# Clean up subreddit name (remove r/ prefix if present)
clean_name = (
subreddit_name[2:] if subreddit_name.startswith("r/") else subreddit_name
)
try:
logger.info(f"Getting info for r/{clean_name}")
subreddit = manager.client.subreddit(clean_name)
# Force fetch subreddit data to verify it exists
_ = subreddit.display_name
return {
"display_name": subreddit.display_name,
"title": subreddit.title,
"description": subreddit.description,
"subscribers": subreddit.subscribers,
"created_utc": subreddit.created_utc,
"over18": subreddit.over18,
"public_description": subreddit.public_description,
"url": subreddit.url,
"active_user_count": getattr(subreddit, "active_user_count", None),
"subreddit_type": getattr(subreddit, "subreddit_type", None),
"submission_type": getattr(subreddit, "submission_type", None),
"quarantine": getattr(subreddit, "quarantine", False),
}
except Exception as e:
logger.error(f"Error getting info for r/{clean_name}: {e}")
if "private" in str(e).lower():
raise ValueError(f"r/{clean_name} is private or cannot be accessed") from e
if "banned" in str(e).lower():
raise ValueError(f"r/{clean_name} has been banned or doesn't exist") from e
if "not found" in str(e).lower():
raise ValueError(f"r/{clean_name} not found") from e
raise RuntimeError(f"Failed to get subreddit info: {e}") from e
@mcp.tool()
def get_trending_subreddits(limit: int = 5) -> "Dict[str, List[Dict[str, Any]]]":
"""Get currently trending subreddits.
Args:
limit: Maximum number of trending subreddits to return (1-50)
Returns:
Dictionary containing list of trending subreddits with their basic info
Raises:
ValueError: If limit is invalid
RuntimeError: For errors during the operation
"""
manager = RedditClientManager()
if not manager.client:
raise RuntimeError("Reddit client not initialized")
limit = max(1, min(50, limit)) # Ensure limit is between 1 and 50
try:
logger.info(f"Getting top {limit} trending subreddits")
popular_subreddits = manager.client.subreddits.popular(limit=limit)
trending = []
for sub in popular_subreddits:
try:
trending.append(
{
"display_name": sub.display_name,
"subscribers": sub.subscribers,
"public_description": sub.public_description,
"over18": sub.over18,
"url": sub.url,
}
)
except Exception as sub_error:
logger.warning(
f"Error processing subreddit {getattr(sub, 'display_name', 'unknown')}: {sub_error}"
)
continue
if not trending:
logger.warning("No trending subreddits found")