github-mcp 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- github_mcp/__init__.py +3 -0
- github_mcp/app.py +3 -0
- github_mcp/client.py +252 -0
- github_mcp/formatting.py +144 -0
- github_mcp/server.py +17 -0
- github_mcp/tools/__init__.py +1 -0
- github_mcp/tools/issues.py +375 -0
- github_mcp/tools/pulls.py +429 -0
- github_mcp/tools/repos.py +686 -0
- github_mcp/tools/search.py +524 -0
- github_mcp-1.1.0.dist-info/METADATA +193 -0
- github_mcp-1.1.0.dist-info/RECORD +15 -0
- github_mcp-1.1.0.dist-info/WHEEL +4 -0
- github_mcp-1.1.0.dist-info/entry_points.txt +3 -0
- github_mcp-1.1.0.dist-info/licenses/LICENSE +21 -0
github_mcp/__init__.py
ADDED
github_mcp/app.py
ADDED
github_mcp/client.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
# MARK: Constants
|
|
10
|
+
|
|
11
|
+
GITHUB_API_BASE = "https://api.github.com"
|
|
12
|
+
GITHUB_API_VERSION = "2022-11-28"
|
|
13
|
+
DEFAULT_ACCEPT = "application/vnd.github+json"
|
|
14
|
+
TIMEOUT = 30.0 # seconds
|
|
15
|
+
|
|
16
|
+
# MARK: Lazy-initialised shared client
|
|
17
|
+
|
|
18
|
+
_client: httpx.AsyncClient | None = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _get_token() -> str:
|
|
22
|
+
"""Return the GitHub PAT from environment variables.
|
|
23
|
+
Checks ``GITHUB_TOKEN`` first, then falls back to ``GITHUB_PAT``.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
str: The GitHub token string.
|
|
27
|
+
|
|
28
|
+
Raises:
|
|
29
|
+
RuntimeError: If neither env var is set, with instructions on how to
|
|
30
|
+
set the token.
|
|
31
|
+
"""
|
|
32
|
+
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GITHUB_PAT")
|
|
33
|
+
if not token:
|
|
34
|
+
raise RuntimeError(
|
|
35
|
+
"GitHub token not found. "
|
|
36
|
+
"Set GITHUB_TOKEN (or GITHUB_PAT) to a fine-grained Personal Access Token. "
|
|
37
|
+
"Create one at https://github.com/settings/tokens?type=beta with the "
|
|
38
|
+
"required permissions (Contents, Issues, Pull requests, Metadata)."
|
|
39
|
+
)
|
|
40
|
+
return token
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _get_client() -> httpx.AsyncClient:
|
|
44
|
+
"""Return (lazily creating) the shared ``httpx.AsyncClient``
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
httpx.AsyncClient: The shared HTTP client instance.
|
|
48
|
+
"""
|
|
49
|
+
global _client
|
|
50
|
+
if _client is None or _client.is_closed:
|
|
51
|
+
token = _get_token()
|
|
52
|
+
_client = httpx.AsyncClient(
|
|
53
|
+
base_url=GITHUB_API_BASE,
|
|
54
|
+
headers={
|
|
55
|
+
"Accept": DEFAULT_ACCEPT,
|
|
56
|
+
"Authorization": f"Bearer {token}",
|
|
57
|
+
"X-GitHub-Api-Version": GITHUB_API_VERSION,
|
|
58
|
+
"User-Agent": "github-mcp/0.1.0",
|
|
59
|
+
},
|
|
60
|
+
timeout=TIMEOUT,
|
|
61
|
+
follow_redirects=True,
|
|
62
|
+
)
|
|
63
|
+
return _client
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# MARK: Core request helpers
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def github_request(
|
|
70
|
+
method: str,
|
|
71
|
+
path: str,
|
|
72
|
+
*,
|
|
73
|
+
params: dict[str, Any] | None = None,
|
|
74
|
+
json: Any = None,
|
|
75
|
+
accept: str | None = None,
|
|
76
|
+
) -> httpx.Response:
|
|
77
|
+
"""Perform a single authenticated GitHub REST API request.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
method (str): HTTP method (GET, POST, PUT, PATCH, DELETE).
|
|
81
|
+
path (str): API path, e.g. ``/repos/owner/repo``.
|
|
82
|
+
params (dict[str, Any] | None): Optional query parameters dict.
|
|
83
|
+
json (Any): Optional request body to serialise as JSON.
|
|
84
|
+
accept (str | None): Override the ``Accept`` header (e.g. for diff responses).
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
httpx.Response: The raw ``httpx.Response`` (caller can call ``.json()`` or ``.text``).
|
|
88
|
+
|
|
89
|
+
Raises:
|
|
90
|
+
httpx.HTTPStatusError: On 4xx/5xx responses (raised by
|
|
91
|
+
``raise_for_status()``).
|
|
92
|
+
"""
|
|
93
|
+
client = _get_client()
|
|
94
|
+
headers = {}
|
|
95
|
+
if accept:
|
|
96
|
+
headers["Accept"] = accept
|
|
97
|
+
|
|
98
|
+
response = await client.request(
|
|
99
|
+
method,
|
|
100
|
+
path,
|
|
101
|
+
params=params,
|
|
102
|
+
json=json,
|
|
103
|
+
headers=headers,
|
|
104
|
+
)
|
|
105
|
+
response.raise_for_status()
|
|
106
|
+
return response
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def github_paginated(
|
|
110
|
+
path: str,
|
|
111
|
+
*,
|
|
112
|
+
params: dict[str, Any] | None = None,
|
|
113
|
+
max_items: int = 100,
|
|
114
|
+
) -> list[Any]:
|
|
115
|
+
"""Fetch all pages of a GitHub list endpoint up to *max_items*.
|
|
116
|
+
|
|
117
|
+
Follows the ``Link: rel="next"`` header automatically.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
path (str): API path for the first page.
|
|
121
|
+
params (dict[str, Any] | None): Base query parameters (``per_page`` will be added/capped).
|
|
122
|
+
max_items (int): Hard cap on total items collected.
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
list[Any]: A flat list of items from all fetched pages.
|
|
126
|
+
"""
|
|
127
|
+
params = dict(params or {})
|
|
128
|
+
params.setdefault("per_page", min(100, max_items))
|
|
129
|
+
|
|
130
|
+
items: list[Any] = []
|
|
131
|
+
client = _get_client()
|
|
132
|
+
url: str | None = path
|
|
133
|
+
|
|
134
|
+
while url and len(items) < max_items:
|
|
135
|
+
response = await client.get(url, params=params)
|
|
136
|
+
response.raise_for_status()
|
|
137
|
+
page_items = response.json()
|
|
138
|
+
if isinstance(page_items, dict):
|
|
139
|
+
# Search responses wrap items under a key like "items"
|
|
140
|
+
page_items = page_items.get("items", [])
|
|
141
|
+
items.extend(page_items)
|
|
142
|
+
|
|
143
|
+
# After the first request, clear per-page params — Link header is absolute
|
|
144
|
+
params = {}
|
|
145
|
+
next_url = _parse_next_link(response.headers.get("link", ""))
|
|
146
|
+
url = next_url
|
|
147
|
+
|
|
148
|
+
return items[:max_items]
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _parse_next_link(link_header: str) -> str | None:
|
|
152
|
+
"""Extract the ``rel="next"`` URL from a GitHub ``Link`` header.
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
link_header (str): Raw ``Link`` header value.
|
|
156
|
+
|
|
157
|
+
Returns:
|
|
158
|
+
str | None: The next-page URL, or ``None`` if absent.
|
|
159
|
+
"""
|
|
160
|
+
for part in link_header.split(","):
|
|
161
|
+
segments = [s.strip() for s in part.split(";")]
|
|
162
|
+
if len(segments) == 2 and segments[1] == 'rel="next"':
|
|
163
|
+
return segments[0].strip("<>")
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
# MARK: Error handling
|
|
168
|
+
def handle_github_error(e: Exception) -> str:
|
|
169
|
+
"""Convert a GitHub API exception into a human-readable, actionable message.
|
|
170
|
+
|
|
171
|
+
Handles the most common error classes:
|
|
172
|
+
- 401 — invalid or expired token
|
|
173
|
+
- 403 + rate-limit header — rate limit exceeded (shows reset time)
|
|
174
|
+
- 403 (other) — permission/scope issue
|
|
175
|
+
- 404 — resource not found
|
|
176
|
+
- 409 — merge conflict or state conflict
|
|
177
|
+
- 422 — validation error (surfaces GitHub's ``errors`` body)
|
|
178
|
+
- Timeout — connection/read timeout
|
|
179
|
+
|
|
180
|
+
Args:
|
|
181
|
+
e (Exception): The caught exception.
|
|
182
|
+
|
|
183
|
+
Returns:
|
|
184
|
+
str: A human-readable error string suitable for returning directly from a
|
|
185
|
+
tool.
|
|
186
|
+
"""
|
|
187
|
+
if isinstance(e, httpx.HTTPStatusError):
|
|
188
|
+
status = e.response.status_code
|
|
189
|
+
if status == 401:
|
|
190
|
+
return (
|
|
191
|
+
"Error 401 Unauthorized: Your GITHUB_TOKEN is invalid or has expired. "
|
|
192
|
+
"Generate a new fine-grained PAT at https://github.com/settings/tokens?type=beta "
|
|
193
|
+
"and update the GITHUB_TOKEN environment variable."
|
|
194
|
+
)
|
|
195
|
+
if status == 403:
|
|
196
|
+
remaining = e.response.headers.get("X-RateLimit-Remaining", "")
|
|
197
|
+
reset_ts = e.response.headers.get("X-RateLimit-Reset", "")
|
|
198
|
+
if remaining == "0" and reset_ts:
|
|
199
|
+
try:
|
|
200
|
+
reset_dt = datetime.fromtimestamp(int(reset_ts), tz=timezone.utc)
|
|
201
|
+
reset_str = reset_dt.strftime("%Y-%m-%d %H:%M UTC")
|
|
202
|
+
except (ValueError, OSError):
|
|
203
|
+
reset_str = reset_ts
|
|
204
|
+
return (
|
|
205
|
+
f"Error 403 Rate Limit Exceeded: GitHub API rate limit reached. "
|
|
206
|
+
f"Resets at {reset_str}. "
|
|
207
|
+
"Consider using a GITHUB_TOKEN to get a higher rate limit (5 000 req/h vs 60)."
|
|
208
|
+
)
|
|
209
|
+
return (
|
|
210
|
+
"Error 403 Forbidden: You do not have permission for this operation. "
|
|
211
|
+
"Check that your GITHUB_TOKEN has the required scopes "
|
|
212
|
+
"(Contents, Issues, Pull requests, Metadata)."
|
|
213
|
+
)
|
|
214
|
+
if status == 404:
|
|
215
|
+
return (
|
|
216
|
+
"Error 404 Not Found: The requested resource does not exist. "
|
|
217
|
+
"Verify the owner, repo, number, or path is correct and that your "
|
|
218
|
+
"token has access to the repository."
|
|
219
|
+
)
|
|
220
|
+
if status == 409:
|
|
221
|
+
return (
|
|
222
|
+
"Error 409 Conflict: The operation could not be completed due to a conflict. "
|
|
223
|
+
"For merges: the branch may have conflicts that must be resolved first. "
|
|
224
|
+
"For file updates: the sha you provided may be stale — fetch the current sha "
|
|
225
|
+
"with github_get_file_contents first."
|
|
226
|
+
)
|
|
227
|
+
if status == 422:
|
|
228
|
+
try:
|
|
229
|
+
body = e.response.json()
|
|
230
|
+
msgs: list[str] = []
|
|
231
|
+
if "message" in body:
|
|
232
|
+
msgs.append(body["message"])
|
|
233
|
+
for err in body.get("errors", []):
|
|
234
|
+
if isinstance(err, dict):
|
|
235
|
+
msgs.append(err.get("message") or str(err))
|
|
236
|
+
else:
|
|
237
|
+
msgs.append(str(err))
|
|
238
|
+
detail = " | ".join(msgs) if msgs else e.response.text
|
|
239
|
+
except Exception:
|
|
240
|
+
detail = e.response.text
|
|
241
|
+
return f"Error 422 Unprocessable Entity: {detail}"
|
|
242
|
+
return f"Error {status}: {e.response.text[:400]}"
|
|
243
|
+
|
|
244
|
+
if isinstance(e, httpx.TimeoutException):
|
|
245
|
+
return (
|
|
246
|
+
"Error: Request to GitHub timed out after 30 seconds. "
|
|
247
|
+
"Try again; if the problem persists the GitHub API may be experiencing issues."
|
|
248
|
+
)
|
|
249
|
+
if isinstance(e, RuntimeError):
|
|
250
|
+
# Re-surface our own token errors unchanged
|
|
251
|
+
return f"Configuration Error: {e}"
|
|
252
|
+
return f"Error: Unexpected error — {type(e).__name__}: {e}"
|
github_mcp/formatting.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ResponseFormat(str, Enum):
|
|
10
|
+
"""Output format for tool responses."""
|
|
11
|
+
|
|
12
|
+
MARKDOWN = "markdown"
|
|
13
|
+
JSON = "json"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# MARK: Timestamp formatting
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def fmt_timestamp(value: str | int | float | None) -> str:
|
|
20
|
+
"""Convert a GitHub timestamp to "YYYY-MM-DD HH:MM UTC".
|
|
21
|
+
Accepts:
|
|
22
|
+
- ISO 8601 strings (``"2024-01-15T10:30:00Z"``)
|
|
23
|
+
- Unix epoch ints/floats
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
value (str | int | float | None): Timestamp string, epoch time, or None.
|
|
27
|
+
Returns:
|
|
28
|
+
str: Formatted string, or the original value as-is if conversion fails.
|
|
29
|
+
"""
|
|
30
|
+
if value is None:
|
|
31
|
+
return "N/A"
|
|
32
|
+
try:
|
|
33
|
+
if isinstance(value, (int, float)):
|
|
34
|
+
dt = datetime.fromtimestamp(value, tz=timezone.utc)
|
|
35
|
+
else:
|
|
36
|
+
# Handle both "Z" and "+00:00" suffixes
|
|
37
|
+
cleaned = str(value).replace("Z", "+00:00")
|
|
38
|
+
dt = datetime.fromisoformat(cleaned)
|
|
39
|
+
if dt.tzinfo is None:
|
|
40
|
+
dt = dt.replace(tzinfo=timezone.utc)
|
|
41
|
+
return dt.strftime("%Y-%m-%d %H:%M UTC")
|
|
42
|
+
except (ValueError, OSError, OverflowError):
|
|
43
|
+
return str(value)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# MARK: List / item formatting helpers
|
|
47
|
+
|
|
48
|
+
# Fields that should always be rendered as timestamps when present
|
|
49
|
+
_TIMESTAMP_FIELDS = frozenset(
|
|
50
|
+
{
|
|
51
|
+
"created_at",
|
|
52
|
+
"updated_at",
|
|
53
|
+
"pushed_at",
|
|
54
|
+
"closed_at",
|
|
55
|
+
"merged_at",
|
|
56
|
+
"committed_date",
|
|
57
|
+
}
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _fmt_field(key: str, value: Any) -> str:
|
|
62
|
+
"""Format a single field value for markdown output.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
key (str): The field name.
|
|
66
|
+
value (Any): The field value.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
str: The formatted value.
|
|
70
|
+
"""
|
|
71
|
+
if key in _TIMESTAMP_FIELDS:
|
|
72
|
+
return fmt_timestamp(value)
|
|
73
|
+
if isinstance(value, bool):
|
|
74
|
+
return "yes" if value else "no"
|
|
75
|
+
if value is None:
|
|
76
|
+
return "N/A"
|
|
77
|
+
return str(value)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def fmt_list_markdown(
|
|
81
|
+
items: list[dict[str, Any]],
|
|
82
|
+
*,
|
|
83
|
+
title: str = "",
|
|
84
|
+
fields: list[str],
|
|
85
|
+
name_field: str = "name",
|
|
86
|
+
) -> str:
|
|
87
|
+
"""Render a compact markdown list from a sequence of dicts.
|
|
88
|
+
|
|
89
|
+
Each item becomes a bullet with the ``name_field`` as the heading and
|
|
90
|
+
one sub-bullet per entry in ``fields`` (if the field is present and
|
|
91
|
+
non-empty). A ``html_url`` field is always appended if present.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
items (list[dict[str, Any]]): List of item dicts (e.g. from a GitHub API list endpoint).
|
|
95
|
+
title (str): Optional markdown heading (rendered as ``## title``).
|
|
96
|
+
fields (list[str]): Field names to include in each item's detail lines.
|
|
97
|
+
name_field (str): Key to use as the item's "name" / primary label.
|
|
98
|
+
|
|
99
|
+
Returns:
|
|
100
|
+
str: Formatted markdown string.
|
|
101
|
+
"""
|
|
102
|
+
lines: list[str] = []
|
|
103
|
+
if title:
|
|
104
|
+
lines.append(f"## {title}")
|
|
105
|
+
lines.append("")
|
|
106
|
+
|
|
107
|
+
if not items:
|
|
108
|
+
lines.append("*No items found.*")
|
|
109
|
+
return "\n".join(lines)
|
|
110
|
+
|
|
111
|
+
for item in items:
|
|
112
|
+
name = (
|
|
113
|
+
item.get(name_field)
|
|
114
|
+
or item.get("title")
|
|
115
|
+
or item.get("login")
|
|
116
|
+
or item.get("sha", "")[:7]
|
|
117
|
+
or "—"
|
|
118
|
+
)
|
|
119
|
+
url = item.get("html_url", "")
|
|
120
|
+
if url:
|
|
121
|
+
lines.append(f"- **[{name}]({url})**")
|
|
122
|
+
else:
|
|
123
|
+
lines.append(f"- **{name}**")
|
|
124
|
+
|
|
125
|
+
for field in fields:
|
|
126
|
+
val = item.get(field)
|
|
127
|
+
if val is None or val == "":
|
|
128
|
+
continue
|
|
129
|
+
pretty_key = field.replace("_", " ").title()
|
|
130
|
+
lines.append(f" - {pretty_key}: {_fmt_field(field, val)}")
|
|
131
|
+
|
|
132
|
+
return "\n".join(lines)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def fmt_json(data: Any) -> str:
|
|
136
|
+
"""Serialise *data* to a pretty-printed JSON string.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
data (Any): Any JSON-serialisable value.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
str: Indented JSON string.
|
|
143
|
+
"""
|
|
144
|
+
return json.dumps(data, indent=2, default=str)
|
github_mcp/server.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
# Import tool modules to register all tools on the shared `mcp` instance.
|
|
4
|
+
import github_mcp.tools.issues # noqa: F401
|
|
5
|
+
import github_mcp.tools.pulls # noqa: F401
|
|
6
|
+
import github_mcp.tools.repos # noqa: F401
|
|
7
|
+
import github_mcp.tools.search # noqa: F401
|
|
8
|
+
from github_mcp.app import mcp
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main() -> None:
|
|
12
|
+
"""Run the GitHub MCP server over stdio transport."""
|
|
13
|
+
mcp.run()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
if __name__ == "__main__":
|
|
17
|
+
main()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Tool sub-package — each module registers tools with the shared FastMCP instance."""
|