-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
455 lines (375 loc) · 14.5 KB
/
Copy pathserver.py
File metadata and controls
455 lines (375 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
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
"""
MCP Server: GitHub Intelligence
Provides Claude with tools to query GitHub's REST API for repository
analytics, issue tracking, pull-request status, contributor insights,
and repository search.
Works without authentication (60 requests/hour).
Set GITHUB_TOKEN in a .env file for higher rate limits (5,000 requests/hour).
"""
from __future__ import annotations
import logging
import os
import sys
from typing import Any, Optional
import httpx
from dotenv import load_dotenv
from mcp.server.fastmcp import FastMCP
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
load_dotenv()
GITHUB_API_BASE = "https://api.github.com"
GITHUB_TOKEN: str | None = os.getenv("GITHUB_TOKEN") or None
REQUEST_TIMEOUT = 30.0 # seconds
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
stream=sys.stderr,
)
logger = logging.getLogger("github-intel")
# ---------------------------------------------------------------------------
# HTTP helpers
# ---------------------------------------------------------------------------
def _build_headers() -> dict[str, str]:
"""Return default headers, including Authorization when a token exists."""
headers: dict[str, str] = {
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
}
if GITHUB_TOKEN:
headers["Authorization"] = f"Bearer {GITHUB_TOKEN}"
return headers
async def _github_request(
method: str,
path: str,
*,
params: dict[str, Any] | None = None,
) -> dict[str, Any] | list[Any]:
"""Execute an authenticated request against the GitHub REST API.
Handles common error conditions:
- 401 Unauthorized (bad token)
- 403 Forbidden / rate-limit exceeded
- 404 Not Found
- Unexpected HTTP errors
- Network / timeout errors
Returns the parsed JSON body on success.
"""
url = f"{GITHUB_API_BASE}{path}"
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
try:
response = await client.request(
method, url, headers=_build_headers(), params=params
)
except httpx.TimeoutException:
raise RuntimeError(
f"Request to {url} timed out after {REQUEST_TIMEOUT}s. "
"GitHub may be experiencing issues — try again shortly."
)
except httpx.HTTPError as exc:
raise RuntimeError(f"Network error while contacting GitHub: {exc}")
# --- Error handling --------------------------------------------------- #
if response.status_code == 401:
raise RuntimeError(
"GitHub returned 401 Unauthorized. "
"Your GITHUB_TOKEN may be invalid or expired."
)
if response.status_code == 403:
remaining = response.headers.get("x-ratelimit-remaining", "?")
reset = response.headers.get("x-ratelimit-reset", "?")
raise RuntimeError(
f"GitHub returned 403 Forbidden. "
f"Rate-limit remaining: {remaining}. "
f"Resets at Unix timestamp: {reset}. "
"Consider adding a GITHUB_TOKEN for 5,000 requests/hour."
)
if response.status_code == 404:
raise RuntimeError(
f"GitHub returned 404 Not Found for {path}. "
"Check that the owner, repo, or resource exists and is public."
)
if response.status_code == 422:
body = response.json()
msg = body.get("message", "Unprocessable Entity")
raise RuntimeError(f"GitHub returned 422: {msg}")
if not response.is_success:
raise RuntimeError(
f"GitHub API error {response.status_code}: {response.text[:500]}"
)
return response.json()
def _rate_limit_note(response_headers: httpx.Headers | None = None) -> str:
"""Build a human-readable rate-limit footnote (best-effort)."""
if GITHUB_TOKEN:
return "Authenticated mode (5,000 requests/hour)."
return "Unauthenticated mode (60 requests/hour). Set GITHUB_TOKEN for higher limits."
# ---------------------------------------------------------------------------
# FastMCP server
# ---------------------------------------------------------------------------
mcp = FastMCP(
"GitHub Intelligence",
description=(
"Query GitHub repositories, issues, pull requests, contributors, "
"and search across all of GitHub — directly from Claude."
),
)
# ---------------------------------------------------------------------------
# Tool 1 — Repository Info
# ---------------------------------------------------------------------------
@mcp.tool()
async def get_repository_info(owner: str, repo: str) -> dict[str, Any]:
"""Retrieve comprehensive information about a GitHub repository.
Returns description, star/fork/issue counts, primary language, license,
creation and last-update timestamps, topics, default branch, size in KB,
and visibility status.
Args:
owner: Repository owner (user or organization).
repo: Repository name.
"""
data: dict[str, Any] = await _github_request("GET", f"/repos/{owner}/{repo}") # type: ignore[assignment]
license_info = data.get("license")
license_name = license_info["spdx_id"] if license_info else None
return {
"full_name": data["full_name"],
"description": data.get("description"),
"homepage": data.get("homepage"),
"stars": data["stargazers_count"],
"forks": data["forks_count"],
"open_issues": data["open_issues_count"],
"watchers": data["subscribers_count"],
"language": data.get("language"),
"license": license_name,
"topics": data.get("topics", []),
"default_branch": data["default_branch"],
"size_kb": data["size"],
"visibility": "private" if data["private"] else "public",
"archived": data["archived"],
"created_at": data["created_at"],
"updated_at": data["updated_at"],
"pushed_at": data["pushed_at"],
"html_url": data["html_url"],
"_note": _rate_limit_note(),
}
# ---------------------------------------------------------------------------
# Tool 2 — Issues
# ---------------------------------------------------------------------------
@mcp.tool()
async def list_issues(
owner: str,
repo: str,
state: str = "open",
labels: Optional[str] = None,
limit: int = 10,
) -> dict[str, Any]:
"""List issues for a GitHub repository with optional filtering.
Args:
owner: Repository owner (user or organization).
repo: Repository name.
state: Filter by state — "open", "closed", or "all". Default: "open".
labels: Comma-separated label names to filter by (e.g. "bug,help wanted").
limit: Maximum number of issues to return (1-100). Default: 10.
"""
if state not in ("open", "closed", "all"):
raise ValueError('state must be "open", "closed", or "all".')
limit = max(1, min(limit, 100))
params: dict[str, Any] = {
"state": state,
"per_page": limit,
"sort": "created",
"direction": "desc",
}
if labels:
params["labels"] = labels
raw: list[dict[str, Any]] = await _github_request( # type: ignore[assignment]
"GET", f"/repos/{owner}/{repo}/issues", params=params
)
# The /issues endpoint also returns pull requests; filter them out.
issues = [item for item in raw if "pull_request" not in item]
results = []
for issue in issues[:limit]:
results.append(
{
"number": issue["number"],
"title": issue["title"],
"state": issue["state"],
"author": issue["user"]["login"],
"labels": [label["name"] for label in issue.get("labels", [])],
"comments": issue["comments"],
"created_at": issue["created_at"],
"updated_at": issue["updated_at"],
"html_url": issue["html_url"],
}
)
return {
"repository": f"{owner}/{repo}",
"filter": {"state": state, "labels": labels},
"total_returned": len(results),
"issues": results,
"_note": _rate_limit_note(),
}
# ---------------------------------------------------------------------------
# Tool 3 — Pull Requests
# ---------------------------------------------------------------------------
@mcp.tool()
async def list_pull_requests(
owner: str,
repo: str,
state: str = "open",
limit: int = 10,
) -> dict[str, Any]:
"""List pull requests for a GitHub repository.
Args:
owner: Repository owner (user or organization).
repo: Repository name.
state: Filter by state — "open", "closed", or "all". Default: "open".
limit: Maximum number of pull requests to return (1-100). Default: 10.
"""
if state not in ("open", "closed", "all"):
raise ValueError('state must be "open", "closed", or "all".')
limit = max(1, min(limit, 100))
params: dict[str, Any] = {
"state": state,
"per_page": limit,
"sort": "created",
"direction": "desc",
}
raw: list[dict[str, Any]] = await _github_request( # type: ignore[assignment]
"GET", f"/repos/{owner}/{repo}/pulls", params=params
)
results = []
for pr in raw[:limit]:
results.append(
{
"number": pr["number"],
"title": pr["title"],
"state": pr["state"],
"author": pr["user"]["login"],
"created_at": pr["created_at"],
"updated_at": pr["updated_at"],
"head_branch": pr["head"]["ref"],
"base_branch": pr["base"]["ref"],
"draft": pr.get("draft", False),
"mergeable": pr.get("mergeable"),
"merged_at": pr.get("merged_at"),
"html_url": pr["html_url"],
}
)
return {
"repository": f"{owner}/{repo}",
"filter": {"state": state},
"total_returned": len(results),
"pull_requests": results,
"_note": _rate_limit_note(),
}
# ---------------------------------------------------------------------------
# Tool 4 — Contributor Stats
# ---------------------------------------------------------------------------
@mcp.tool()
async def get_contributor_stats(
owner: str,
repo: str,
limit: int = 10,
) -> dict[str, Any]:
"""Get the top contributors to a GitHub repository, sorted by commit count.
Args:
owner: Repository owner (user or organization).
repo: Repository name.
limit: Maximum number of contributors to return (1-100). Default: 10.
"""
limit = max(1, min(limit, 100))
params: dict[str, Any] = {"per_page": limit}
raw: list[dict[str, Any]] = await _github_request( # type: ignore[assignment]
"GET", f"/repos/{owner}/{repo}/contributors", params=params
)
results = []
for idx, contributor in enumerate(raw[:limit], start=1):
results.append(
{
"rank": idx,
"username": contributor["login"],
"contributions": contributor["contributions"],
"avatar_url": contributor["avatar_url"],
"profile_url": contributor["html_url"],
}
)
return {
"repository": f"{owner}/{repo}",
"total_returned": len(results),
"contributors": results,
"_note": _rate_limit_note(),
}
# ---------------------------------------------------------------------------
# Tool 5 — Repository Search
# ---------------------------------------------------------------------------
@mcp.tool()
async def search_repositories(
query: str,
language: Optional[str] = None,
sort: str = "stars",
limit: int = 10,
) -> dict[str, Any]:
"""Search GitHub repositories by keyword, with optional language filter.
Args:
query: Search query (e.g. "machine learning", "fastapi framework").
language: Filter results by primary language (e.g. "python", "rust").
sort: Sort order — "stars", "forks", or "updated". Default: "stars".
limit: Maximum number of results to return (1-100). Default: 10.
"""
if sort not in ("stars", "forks", "updated"):
raise ValueError('sort must be "stars", "forks", or "updated".')
limit = max(1, min(limit, 100))
q = query
if language:
q += f" language:{language}"
params: dict[str, Any] = {
"q": q,
"sort": sort,
"order": "desc",
"per_page": limit,
}
data: dict[str, Any] = await _github_request( # type: ignore[assignment]
"GET", "/search/repositories", params=params
)
results = []
for item in data.get("items", [])[:limit]:
license_info = item.get("license")
results.append(
{
"full_name": item["full_name"],
"description": item.get("description"),
"stars": item["stargazers_count"],
"forks": item["forks_count"],
"language": item.get("language"),
"license": license_info["spdx_id"] if license_info else None,
"updated_at": item["updated_at"],
"html_url": item["html_url"],
}
)
return {
"query": query,
"language_filter": language,
"sort_by": sort,
"total_results_available": data.get("total_count", 0),
"total_returned": len(results),
"repositories": results,
"_note": _rate_limit_note(),
}
# ---------------------------------------------------------------------------
# Startup logging
# ---------------------------------------------------------------------------
def _log_startup() -> None:
"""Log authentication mode on startup."""
if GITHUB_TOKEN:
masked = GITHUB_TOKEN[:4] + "..." + GITHUB_TOKEN[-4:]
logger.info("Authenticated mode enabled (token: %s).", masked)
logger.info("Rate limit: 5,000 requests/hour.")
else:
logger.info("Running in unauthenticated mode.")
logger.info(
"Rate limit: 60 requests/hour. "
"Set GITHUB_TOKEN in .env for higher limits."
)
# ---------------------------------------------------------------------------
# Entrypoint
# ---------------------------------------------------------------------------
if __name__ == "__main__":
_log_startup()
mcp.run()