Spaces:
Sleeping
Sleeping
File size: 3,598 Bytes
a901719 3bdfbbe a901719 14b9237 a901719 |
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 |
from mcp.server.fastmcp import FastMCP
import praw
import re
import os
from typing import Optional
mcp = FastMCP("Reddit")
# Initialize Reddit client once with env vars
def get_reddit_client():
client_id = os.getenv('REDDIT_CLIENT_ID')
client_secret = os.getenv('REDDIT_CLIENT_SECRET')
user_agent = os.getenv('REDDIT_USER_AGENT', 'MCP Reddit Tool v1.0')
print(client_id,client_secret,user_agent)
if not client_id or not client_secret:
raise ValueError("Missing REDDIT_CLIENT_ID or REDDIT_CLIENT_SECRET environment variables")
return praw.Reddit(
client_id=client_id,
client_secret=client_secret,
user_agent=user_agent,
)
@mcp.tool()
def get_reddit_thread(
url: str,
max_comment_depth: Optional[int] = None
) -> str:
"""Get full Reddit thread as formatted text.
Args:
url: Reddit post URL
max_comment_depth: Max depth of comments to include (None=all, 0=no comments)
Returns:
Formatted text of Reddit post and comments
"""
try:
reddit = get_reddit_client()
# Get the submission
submission = reddit.submission(url=url)
# Build post header
author = submission.author.name if submission.author else "[deleted]"
selftext = re.sub(r'\n+', ' ', submission.selftext) if submission.selftext else ""
output = [
f"Title: {submission.title}",
f"Author: {author}",
f"Score: {submission.score} points",
f"Comments: {submission.num_comments}",
]
if selftext:
output.append(f"\nPost text: {selftext}")
# Add comments if requested
if max_comment_depth != 0:
output.append("\n\n--- COMMENTS ---")
# Fetch all comments
submission.comments.replace_more(limit=None)
# Process comments recursively
def process_comments(comments, depth=0):
result = []
if max_comment_depth is not None and depth >= max_comment_depth:
return result
for comment in comments:
if isinstance(comment, praw.models.MoreComments):
continue
# Format comment with pipe indentation
indent = "| " * depth
author = comment.author.name if comment.author else "[deleted]"
body = re.sub(r'\n+', ' ', comment.body)
score = comment.score
result.append(f"{indent}{author} ({score} points): {body}")
# Add replies
if comment.replies:
result.extend(process_comments(comment.replies, depth + 1))
return result
comment_lines = process_comments(submission.comments)
output.extend(comment_lines)
return "\n".join(output)
except ValueError as e:
return f"❌ Configuration error: {str(e)}"
except praw.exceptions.InvalidURL:
return "❌ Invalid Reddit URL"
except praw.exceptions.NotFound:
return "❌ Post not found"
except praw.exceptions.Forbidden:
return "❌ Access forbidden - check your credentials"
except Exception as e:
return f"❌ Error: {str(e)}"
if __name__ == "__main__":
mcp.run() |