-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathscrape.py
More file actions
380 lines (324 loc) · 14.5 KB
/
Copy pathscrape.py
File metadata and controls
380 lines (324 loc) · 14.5 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
import time
import github.Auth
import requests
import re
import os
import sqlite3
import json
from typing import List, Tuple
from dotenv import load_dotenv
from langchain_core.documents.base import Document
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
from github import RateLimitExceededException
from server_list_sources import get_all_sources
# ---------------------------------------------------------------------
# If fetch_readme is in the same file, this import isn't needed.
# If it's in another module, replace the direct call below accordingly.
# from my_readme_fetcher import fetch_readme
# ---------------------------------------------------------------------
from config import *
BASE_DIR = os.getenv("DATADIR", "db")
DB_PATH = os.path.join(BASE_DIR, 'server_list.db')
TXT_PATH = os.path.join(BASE_DIR, 'mcp_servers.txt')
INDEX_DIR = os.path.join(BASE_DIR, 'faiss_index')
# ---------------------------
# DB: schema & migration
# ---------------------------
def create_db_and_table(db_path):
os.makedirs(os.path.dirname(db_path), exist_ok=True)
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS servers (
name TEXT,
description TEXT,
url TEXT PRIMARY KEY,
readme_content TEXT,
fetch_error TEXT,
require_api_key INTEGER DEFAULT 0,
config_setup_cmd TEXT,
additional_cmd TEXT
)
''')
conn.commit()
conn.close()
def read_servers_from_txt(txt_path):
strict_regex = re.compile(r'^-\s*\[(?P<name>[^\]]+)\]\((?P<url>[^)]+)\)\s*-\s*(?P<desc>.+\S)\s*$') # match everything after second hyphen as description
fallback_regex = re.compile(r'^-\s*\[(?P<name>[^\]]+)\]\((?P<url>[^)]+)\)\s*(?P<desc>.+\S)\s*$') # if second hyphen isn't present, match everything after url
servers = []
if not os.path.exists(txt_path):
return servers
with open(txt_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
match = strict_regex.match(line) or fallback_regex.match(line)
if not match:
print(f"Skipping unrecognized line format: {line}")
continue
name, url, description = match.groups()
servers.append((name, description, url))
return servers
# ---------------------------
# README integration
# ---------------------------
from helpers.github_urls import _parse_github_url, API_KEY_PATTERN_RE
def fetch_readme(github_url: str) -> str:
"""
Fetch the README content for a GitHub URL. If the URL is not for GitHub, returns empty content.
Attempts to locate the README.md in the indicated directory (e.g., for
https://github.com/owner/repo/tree/main/path, it fetches README.md inside path).
First tries raw.githubusercontent.com; if that fails, falls back to PyGithub API.
Returns JSON string with keys:
- status: "success" or "error: <message>"
- require_api_key: bool (heuristic scan)
- content: README text (empty on error)
- REMINDER: only present when require_api_key is True
"""
import os
import json
import requests
try:
parsed = _parse_github_url(github_url)
if parsed is None:
# Not parseable as GitHub URL: return empty content per spec
result = {
"status": "error: no support for non github urls for now. ",
"require_api_key": False,
"content": ""
}
return json.dumps(result)
owner, repo_name, branch, subpath = parsed
# Attempt fetching raw README via raw.githubusercontent.com
# Determine branch: if not in URL, we may need to query API for default branch
use_branch = branch
if subpath:
# Directory: look for README.md inside that dir
# Avoid naive strip; ensure path ends without trailing slash
normalized_subpath = subpath.rstrip("/").lstrip("/")
readme_path_fragment = f"{normalized_subpath}/README.md"
else:
# Root: README.md at root
readme_path_fragment = "README.md"
raw_content = None
# If branch unknown, try common defaults first before hitting API
candidate_branches = []
if use_branch:
candidate_branches.append(use_branch)
else:
candidate_branches.extend(["main", "master"])
# We'll only query PyGithub for default branch if raw attempts fail and PyGithub is available
for br in candidate_branches:
raw_url = f"https://raw.githubusercontent.com/{owner}/{repo_name}/{br}/{readme_path_fragment}"
try:
# NO Header when visiting raw github! Only need header when visiting api.github.com
resp = requests.get(raw_url, timeout=10)
if resp.status_code == 200:
raw_content = resp.text
use_branch = br
break
except Exception:
# swallow and continue
pass
# If still no content, try to get default branch via API and fetch raw README there
if raw_content is None:
print(f"Fetching README from GitHub API for {owner}/{repo_name} on branch {use_branch}")
try:
from github import Github
token = os.getenv("GITHUB_TOKEN", None)
gh = Github(auth=github.Auth.Token(token)) if token else Github()
repo = gh.get_repo(f"{owner}/{repo_name}")
if not use_branch:
use_branch = getattr(repo, "default_branch", None)
if use_branch:
raw_url = f"https://raw.githubusercontent.com/{owner}/{repo_name}/{use_branch}/{readme_path_fragment}"
resp = requests.get(raw_url, headers=HEADER, timeout=10)
if resp.status_code == 200:
raw_content = resp.text
else:
# log raw url failed
print(f"Raw fetch failed for {raw_url} with status {resp.status_code}")
# Fallback: use GitHub API to get the README for that directory
if raw_content is None:
target_dir = subpath or ""
candidate_readme_path = (
target_dir if target_dir.lower().endswith("readme.md") else f"{target_dir}/README.md"
).lstrip("/")
try:
content_file = repo.get_contents(candidate_readme_path, ref=use_branch)
if content_file and getattr(content_file, "decoded_content", None):
raw_content = content_file.decoded_content.decode()
except Exception:
# Last resort: root README
try:
root_readme = repo.get_readme(ref=use_branch)
raw_content = root_readme.decoded_content.decode()
except Exception:
pass
except Exception:
# swallow to allow downstream error handling
pass
if raw_content is None:
result = {
"status": f"error: could not locate README in '{github_url}' (tried raw fetch and API)",
"require_api_key": False,
"content": ""
}
return json.dumps(result)
# Scan for API-key patterns
require_api_key = bool(API_KEY_PATTERN_RE.search(raw_content))
result = {
"status": "success",
"require_api_key": require_api_key,
"content": raw_content
}
if require_api_key:
result[
"REMINDER"] = "IMMEDIATELY INSTRUCT THE USER TO GET THE API KEY. PROVIDE THEM WITH THE URL IF POSSIBLE."
except Exception as e:
result = {
"status": f"error: {e}",
"require_api_key": False,
"content": ""
}
return json.dumps(result)
def _extract_readme_fields(github_url: str):
"""
Calls your fetch_readme(github_url) and returns a tuple:
(readme_content, fetch_error, require_api_key_int)
"""
try:
result_raw = fetch_readme(github_url)
data = json.loads(result_raw) if isinstance(result_raw, str) else result_raw
status = data.get("status", "")
content = data.get("content", "") or ""
require_api_key = 1 if data.get("require_api_key", False) else 0
# If status starts with "error:", stash the message in fetch_error, else ""
fetch_error = status if (isinstance(status, str) and status.lower().startswith("error")) else ""
return content, fetch_error, require_api_key
except RateLimitExceededException as e:
# wait and retry in 1 hour
print("GitHub API rate limit exceeded. Sleeping for 1 hour before retrying...")
time.sleep(3600) # sleep for 1 hour
return _extract_readme_fields(github_url)
except Exception as e:
# Defensive: treat as fetch error but keep the row
return "", f"error: {e}", 0
# ---------------------------
# Updater
# ---------------------------
def update_db(db_path, servers):
"""
servers: iterable of (name, description, url)
- Validates URL reachability
- Fetches README + API-key flag using fetch_readme
- Upserts by URL (URL is the conflict target). Existing rows are overwritten.
"""
conn = sqlite3.connect(db_path)
c = conn.cursor()
for name, description, url in servers:
try:
response = requests.get(url, headers=HEADER, timeout=10)
if response.status_code == 200:
readme_content, fetch_error, require_api_key = _extract_readme_fields(url)
# Overwrite the entire row when the same URL already exists.
c.execute('''
INSERT INTO servers (name, description, url, readme_content, fetch_error, require_api_key)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(url) DO UPDATE SET
name = excluded.name,
description = excluded.description,
readme_content = excluded.readme_content,
fetch_error = excluded.fetch_error,
require_api_key = excluded.require_api_key
''', (name, description, url, readme_content, fetch_error, require_api_key))
print(f"Upserted by URL: {url} (name={name}) "
f"(api_key={require_api_key}, err={fetch_error if fetch_error else 'no'})")
elif response.status_code == 404:
# Remove unreachable entries (by URL)
c.execute('DELETE FROM servers WHERE url = ?', (url,))
elif response.status_code == 403:
print(f"Access denied for {url}: HTTP 403 Forbidden, skipping.")
else:
print(f"Skipping {url}: HTTP {response.status_code}")
except Exception as e:
# Record error but still upsert so we keep a row keyed by URL
readme_content, fetch_error, require_api_key = "", f"error: {e}", 0
c.execute('''
INSERT INTO servers (name, description, url, readme_content, fetch_error, require_api_key)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(url) DO UPDATE SET
name = excluded.name,
description = excluded.description,
readme_content = excluded.readme_content,
fetch_error = excluded.fetch_error,
require_api_key = excluded.require_api_key
''', (name, description, url, readme_content, fetch_error, require_api_key))
print(f"Error accessing {url}: {e}")
conn.commit()
conn.close()
# ---------------------------
# Embeddings (now include README)
# ---------------------------
def truncate_readme(readme):
"""
Truncate README content to include everything from the first '#'
and stop at the next non-consecutive '#'. If no such section exists,
use the entire content after the first '#'.
"""
lines = readme.splitlines()
truncated = []
found_first_section = False
for i, line in enumerate(lines):
if line.strip().startswith("#"):
if not found_first_section:
found_first_section = True
elif i > 0 and not lines[i - 1].strip().startswith("#"):
break
if found_first_section:
truncated.append(line)
return "\n".join(truncated)
def generate_embeddings(db_path):
conn = sqlite3.connect(db_path)
c = conn.cursor()
# include README content when present
c.execute('SELECT name, description, url, readme_content FROM servers')
rows = c.fetchall()
conn.close()
docs = []
for name, desc, url, readme in rows:
# Combine description + README for richer retrieval
readme = truncate_readme(readme or "") # Only get the intro section of the README
page_content = ((desc or "") + "\n\n" + (readme or "")).strip()
if not page_content:
# Avoid empty docs that can cause embedding errors
page_content = desc or ""
docs.append(Document(page_content=page_content, metadata={"name": name, "url": url}))
embeddings = OpenAIEmbeddings()
vector_store = FAISS.from_documents(docs, embeddings)
os.makedirs(INDEX_DIR, exist_ok=True)
vector_store.save_local(INDEX_DIR)
return vector_store
# ---------------------------
# Main workflow
# ---------------------------
if __name__ == '__main__':
# 1. Scrape and write to text file
sources = get_all_sources()
os.makedirs(os.path.dirname(TXT_PATH), exist_ok=True)
with open(TXT_PATH, 'w', encoding='utf-8') as f:
f.write("\n".join(sources))
print(f"Scraped {len(sources)} server entries to {TXT_PATH}")
# 2. Initialize / migrate DB
create_db_and_table(DB_PATH)
# 3. Read scraped entries and update DB (with README + flags)
servers = read_servers_from_txt(TXT_PATH)
if servers:
update_db(DB_PATH, servers)
else:
print(f"No valid servers found in {TXT_PATH}")
# 4. Generate and save embeddings (now includes README content)
generate_embeddings(DB_PATH)
print("Finished scraping, DB update, and embedding generation.")