Jofthomas commited on
Commit
fb8e780
·
verified ·
1 Parent(s): 388495e

Upload 4 files

Browse files
Files changed (4) hide show
  1. Dockerfile +19 -0
  2. app.py +223 -0
  3. fastmcp.json +10 -0
  4. requirements.txt +5 -0
Dockerfile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ # Set the working directory in the container
4
+ WORKDIR /app
5
+
6
+ COPY requirements.txt .
7
+
8
+ RUN pip install --no-cache-dir -r requirements.txt
9
+
10
+ COPY . .
11
+
12
+ # Create directory for battle replays with proper permissions
13
+ RUN mkdir -p battle_replays && chmod 755 battle_replays
14
+
15
+ EXPOSE 7860
16
+
17
+ ENV PORT=7860
18
+
19
+ CMD ["python", "app.py"]
app.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from typing import List, Optional, Literal
5
+
6
+ import httpx
7
+ import feedparser
8
+ from pydantic import BaseModel, Field, HttpUrl
9
+
10
+ from fastmcp import FastMCP
11
+ from mistralai import Mistral
12
+
13
+
14
+ mcp = FastMCP(
15
+ name="reddit-painpoints",
16
+ description="Monitor r/MistralAI and extract community pain points (with links)",
17
+ host="0.0.0.0",
18
+ port=7860,
19
+ )
20
+
21
+ MISTRAL_MODEL = "mistral-medium-2508"
22
+
23
+ class PainPoint(BaseModel):
24
+ """Structured representation of a user pain point extracted from a Reddit post."""
25
+
26
+ title: str = Field(..., description="Short title of the pain point")
27
+ summary: str = Field(..., description="One-sentence summary of the problem")
28
+ url: HttpUrl = Field(..., description="URL to the original Reddit post")
29
+ score: int = Field(..., description="Reddit score (upvotes minus downvotes)")
30
+ created_utc: float = Field(..., description="Post creation time (Unix seconds)")
31
+ post_id: str = Field(..., description="Reddit post ID")
32
+ flair: Optional[str] = Field(None, description="Post flair, if present")
33
+
34
+
35
+ class PainPointDecision(BaseModel):
36
+ decision: Literal["YES", "NO"]
37
+ reason: Optional[str] = None
38
+
39
+
40
+ class PainPointGenerated(BaseModel):
41
+ title: str
42
+ summary: str
43
+
44
+
45
+ def _fetch_subreddit_new(subreddit: str, limit: int) -> list[dict]:
46
+ """Fetch 'new' posts; fallback to RSS if JSON is blocked."""
47
+ json_url = f"https://www.reddit.com/r/{subreddit}/new.json?limit={limit}"
48
+ headers = {
49
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) FastMCP-RedditPainPoints/1.0 (+https://example.com)",
50
+ "Accept": "application/json, text/plain, */*",
51
+ "Accept-Language": "en-US,en;q=0.9",
52
+ }
53
+
54
+ try:
55
+ with httpx.Client(timeout=httpx.Timeout(15.0), headers=headers) as client:
56
+ response = client.get(json_url, follow_redirects=True)
57
+ response.raise_for_status()
58
+ payload = response.json()
59
+ children = payload.get("data", {}).get("children", [])
60
+ print(f"Reddit fetch source: JSON API ({len(children)} items)")
61
+ return [child.get("data", {}) for child in children]
62
+ except Exception:
63
+ # RSS fallback
64
+ feed_url = f"https://www.reddit.com/r/{subreddit}/new/.rss"
65
+ feed = feedparser.parse(feed_url)
66
+ posts: list[dict] = []
67
+ for entry in feed.entries[:limit]:
68
+ # Attempt to extract id and score if present (RSS is limited)
69
+ link = entry.get("link") or ""
70
+ title = entry.get("title") or ""
71
+ # created: use published_parsed if available
72
+ created_utc = 0.0
73
+ if getattr(entry, "published_parsed", None):
74
+ try:
75
+ import calendar
76
+
77
+ created_utc = float(calendar.timegm(entry.published_parsed))
78
+ except Exception:
79
+ created_utc = 0.0
80
+ posts.append(
81
+ {
82
+ "title": title,
83
+ "selftext": "",
84
+ "score": 0,
85
+ "created_utc": created_utc,
86
+ "id": entry.get("id") or "",
87
+ "permalink": "",
88
+ "url": link,
89
+ "link_flair_text": None,
90
+ }
91
+ )
92
+ print(f"Reddit fetch source: RSS fallback ({len(posts)} items)")
93
+ return posts
94
+
95
+
96
+ def _get_mistral_client() -> Mistral:
97
+ api_key = os.environ.get("MISTRAL_API_KEY")
98
+ if not api_key:
99
+ raise RuntimeError("MISTRAL_API_KEY environment variable is required for AI-based extraction")
100
+ return Mistral(api_key=api_key)
101
+
102
+
103
+ def _ai_should_extract_painpoint(client: Mistral, title: str, selftext: str) -> bool:
104
+ """Use Mistral structured output to decide if the post is a pain point."""
105
+ content = (
106
+ "You are a strict classifier deciding if a Reddit post describes a concrete pain point "
107
+ "about Mistral AI usage (APIs, models, SDKs, deployment, errors, performance, limitations).\n\n"
108
+ "Return JSON with decision YES/NO and a brief reason."
109
+ )
110
+
111
+ user_text = (
112
+ f"Title: {title}\n\n"
113
+ f"Body: {selftext or '(none)'}\n\n"
114
+ "Does this describe a real problem/pain point that warrants tracking?"
115
+ )
116
+
117
+ resp = client.chat.parse(
118
+ model=MISTRAL_MODEL,
119
+ messages=[
120
+ {"role": "system", "content": content},
121
+ {"role": "user", "content": user_text},
122
+ ],
123
+ response_format=PainPointDecision,
124
+ temperature=0,
125
+ max_tokens=64,
126
+ )
127
+
128
+ parsed: PainPointDecision = resp.choices[0].message.parsed # type: ignore[attr-defined]
129
+ print(f"AI classify: {parsed.decision}")
130
+ return parsed.decision == "YES"
131
+
132
+
133
+ def _ai_generate_title_summary(client: Mistral, title: str, selftext: str) -> PainPointGenerated:
134
+ """Use Mistral structured output to produce a concise title and summary."""
135
+ content = (
136
+ "You generate a clear, concise pain point title and a one-sentence summary that captures the core issue.\n"
137
+ "Do not add links or metadata. Keep the summary <= 240 characters."
138
+ )
139
+ user_text = (
140
+ f"Original Title: {title}\n\n"
141
+ f"Body: {selftext or '(none)'}\n\n"
142
+ "If insufficient information, infer a short neutral title and a crisp summary."
143
+ )
144
+
145
+ resp = client.chat.parse(
146
+ model=MISTRAL_MODEL,
147
+ messages=[
148
+ {"role": "system", "content": content},
149
+ {"role": "user", "content": user_text},
150
+ ],
151
+ response_format=PainPointGenerated,
152
+ temperature=0,
153
+ max_tokens=128,
154
+ )
155
+
156
+ return resp.choices[0].message.parsed # type: ignore[return-value, attr-defined]
157
+
158
+
159
+ @mcp.tool(description="Scan r/MistralAI for problem-like posts using AI and return extracted pain points.")
160
+ def scan_mistralai_pain_points(limit: int = 50, min_score: int = 0) -> List[PainPoint]:
161
+ """
162
+ Fetch recent posts from r/MistralAI and extract a list of pain points using a two-step AI flow:
163
+ 1) Classify each post as a pain point (YES/NO)
164
+ 2) If YES, generate a concise title and summary via structured outputs
165
+
166
+ - limit: Maximum posts to scan (<=100)
167
+ - min_score: Minimum Reddit score to include
168
+
169
+ Requires MISTRAL_API_KEY in environment.
170
+ """
171
+ raw_posts = _fetch_subreddit_new("MistralAI", max(1, min(limit, 100)))
172
+ client = _get_mistral_client()
173
+
174
+ pain_points: List[PainPoint] = []
175
+ for post in raw_posts:
176
+ title = post.get("title", "").strip()
177
+ selftext = post.get("selftext", "") or ""
178
+ score = int(post.get("score", 0) or 0)
179
+
180
+ if score < min_score:
181
+ continue
182
+
183
+ try:
184
+ should = _ai_should_extract_painpoint(client, title, selftext)
185
+ except Exception:
186
+ # On AI failure, skip the post to avoid false positives
187
+ print("AI classify failed; skipping post")
188
+ continue
189
+
190
+ if not should:
191
+ continue
192
+
193
+ try:
194
+ gen = _ai_generate_title_summary(client, title, selftext)
195
+ ai_title = gen.title.strip()
196
+ ai_summary = gen.summary.strip()
197
+ except Exception:
198
+ # If generation fails, fall back to minimal safe defaults
199
+ print("AI generation failed; using fallback title/summary")
200
+ ai_title = title
201
+ ai_summary = (selftext or title)[:240]
202
+
203
+ permalink = post.get("permalink") or ""
204
+ full_url = f"https://www.reddit.com{permalink}" if permalink else post.get("url_overridden_by_dest") or post.get("url") or ""
205
+
206
+ pain_points.append(
207
+ PainPoint(
208
+ title=ai_title or title,
209
+ summary=ai_summary,
210
+ url=full_url,
211
+ score=score,
212
+ created_utc=float(post.get("created_utc", 0.0) or 0.0),
213
+ post_id=str(post.get("id", "")),
214
+ flair=post.get("link_flair_text"),
215
+ )
216
+ )
217
+
218
+ print(f"Extraction complete: {len(pain_points)} pain points")
219
+ return pain_points
220
+
221
+
222
+ if __name__ == "__main__":
223
+ mcp.run(transport="http")
fastmcp.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "reddit-painpoints",
3
+ "description": "MCP server that monitors r/MistralAI and extracts community pain points with links",
4
+ "entrypoint": "server.py",
5
+ "transport": "streamable-http",
6
+ "http": {
7
+ "host": "0.0.0.0",
8
+ "port": 7860
9
+ }
10
+ }
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastmcp>=2.12.2
2
+ httpx>=0.27.0
3
+ pydantic>=2.7.0
4
+ mistralai>=1.5.0
5
+ feedparser>=6.0.11