github-mcp 1.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lucas
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,193 @@
1
+ Metadata-Version: 2.4
2
+ Name: github-mcp
3
+ Version: 1.1.0
4
+ Summary: Local GitHub MCP server exposing GitHub REST API via FastMCP stdio transport
5
+ License: MIT License
6
+
7
+ Copyright (c) 2026 Lucas
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+ License-File: LICENSE
27
+ Keywords: github,mcp,fastmcp,stdio,rest api,search
28
+ Author: Lucas Waetzig
29
+ Author-email: development@waetzig.net
30
+ Requires-Python: >=3.12
31
+ Classifier: Development Status :: 5 - Production/Stable
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: Intended Audience :: Science/Research
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: OS Independent
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3.12
38
+ Classifier: Programming Language :: Python :: 3.13
39
+ Classifier: Topic :: Scientific/Engineering
40
+ Classifier: Topic :: Software Development :: Libraries
41
+ Requires-Dist: httpx (>=0.28.1,<0.29.0)
42
+ Requires-Dist: mcp[cli] (>=1.0.0)
43
+ Requires-Dist: pydantic (>=2.13.4,<3.0.0)
44
+ Project-URL: Documentation, https://personal-public-packages.gitlab.io/github-mcp
45
+ Project-URL: Homepage, https://github.com/LWaetzig/github-mcp
46
+ Project-URL: Issues, https://github.com/LWaetzig/github-mcp/issues
47
+ Project-URL: Repository, https://github.com/LWaetzig/github-mcp
48
+ Description-Content-Type: text/markdown
49
+
50
+ # github-mcp
51
+
52
+ An MCP (Model COntext Protocol) server that gives AI assistants direct access to GitHub. Exposing ~22 GitHub REST tools
53
+ covering repos, files, issues, pull requests, as well as searching.
54
+
55
+ ## Table of Contents
56
+
57
+ 1. [Features](#features)
58
+ 2. [Installation](#installation)
59
+ 3. [Usage]()
60
+ 4. [Contributing]()
61
+
62
+ ## Features
63
+
64
+ A single stdio MCP server (built on [FastMCP](https://github.com/modelcontextprotocol/python-sdk)) exposing **23 GitHub REST tools** grouped into four areas:
65
+
66
+ - **Repositories & files** — `github_list_repos`, `github_get_repo`, `github_list_branches`, `github_list_commits`, `github_get_file_contents`, `github_list_directory`, `github_create_or_update_file`, `github_create_branch`
67
+ - **Issues** — `github_list_issues`, `github_get_issue`, `github_create_issue`, `github_update_issue`, `github_add_issue_comment`
68
+ - **Pull requests** — `github_list_pull_requests`, `github_get_pull_request`, `github_create_pull_request`, `github_merge_pull_request`, `github_add_pr_comment`
69
+ - **Search** — `github_search_repositories`, `github_search_code`, `github_search_issues`, `github_search_users`, `github_search_commits`
70
+
71
+ Under the hood:
72
+
73
+ - **Async HTTP** via a shared, lazily-initialised `httpx.AsyncClient` against the pinned GitHub API version (`2022-11-28`).
74
+ - **Automatic pagination** — list endpoints follow the `Link: rel="next"` header up to a configurable item cap.
75
+ - **Typed inputs** — every tool validates its arguments with Pydantic models.
76
+ - **Actionable errors** — common GitHub failures (401, 403/rate-limit with reset time, 404, 409, 422, timeouts) are translated into clear, human-readable messages.
77
+ - **Flexible auth** — reads a fine-grained PAT from `GITHUB_TOKEN`, falling back to `GITHUB_PAT`.
78
+
79
+ ## Installation
80
+
81
+ ### Prerequisites
82
+
83
+ - `Python 3.12` or later
84
+ - Dependencies `mcp[cli]>=1.0.0`, `httpx>=0.27.0`, `pydantic>=2.0.0` (see [pyproject.toml](pyproject.toml)) (project uses `poetry` for dependency management)
85
+
86
+
87
+ ### Install from PyPi
88
+
89
+ ```bash
90
+ pip install github-mcp
91
+
92
+ # or using poetry
93
+ poetry add github-mcp
94
+ ```
95
+
96
+ ### Build from source
97
+
98
+ ```bash
99
+ git clone https://github.com/LWaetzig/github-mcp.git
100
+ cd github-mcp
101
+ pip install -e .
102
+ ```
103
+
104
+ ## Usage
105
+
106
+ - Detailed documentation about single tools can be found this [sphinx documentation]()
107
+
108
+ ### Prerequisites
109
+
110
+ #### Create a fine-grained Personal Access Token (PAT)
111
+
112
+ 1. Go to **GitHub -> Settings -> Developer settings -> Personal access tokens -> Fine-grained tokens** (direct link: <https://github.com/settings/tokens?type=beta>)
113
+ 2. Generate new token
114
+ 3. Set **Resource owner** and **Repository access** as appropriate
115
+ 4. Grant these **Repository permissions** (minimum for full read + write):
116
+
117
+ | Permission | Access level | Used by tools |
118
+ | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
119
+ | **Metadata** | Read-only | All tools |
120
+ | **Contents** | Read and write | `github_get_file_contents`, `github_list_directory`, `github_list_commits`, `github_create_or_update_file`, `github_create_branch` |
121
+ | **Issues** | Read and write | `github_list_issues`, `github_get_issue`, `github_create_issue`, `github_update_issue`, `github_add_issue_comment` |
122
+ | **Pull requests** | Read and write | `github_list_pull_requests`, `github_get_pull_request`, `github_create_pull_request`, `github_merge_pull_request`, `github_add_pr_comment` |
123
+
124
+ > **Read-only subset**: grant only **Read-only** access to Contents, Issues, Pull requests, and Metadata if you don't need write tools.
125
+
126
+
127
+ ```bash
128
+ export GITHUB_TOKEN=github_pat_...
129
+ ```
130
+
131
+ Or copy `.env.example` -> `.env` and fill in the token (load with `source .env`).
132
+
133
+
134
+ ### Integrating with Claude Desktop
135
+
136
+ Add the server to your Claude Desktop configuration:
137
+
138
+ | Platform | Path |
139
+ |---|---|
140
+ | macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
141
+ | Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
142
+
143
+ Add the `github` entry under `mcpServers`, replacing the path with the absolute path to your clone:
144
+
145
+ ```json
146
+ {
147
+ "mcpServers" : {
148
+ "github" : {
149
+ "command" : "python",
150
+ "args" : ["-m", "github-mcp"],
151
+ "env" : {
152
+ "GITHUB_TOKEN" : "github_pat_..."
153
+ }
154
+ }
155
+ }
156
+ }
157
+ ```
158
+
159
+ Restart Claude Desktop. You should see the github tools available int he tool picker.
160
+
161
+ ### Integration with Other MCP Clients
162
+
163
+ Any MCP client (e.g. Cline, GitHub Copilot, or custm tools) can use this server.
164
+ Configuration depends on your assistant, in most cases there is a `config` to change.
165
+
166
+
167
+ ## Contribution
168
+
169
+ Contributions are welcome! Please:
170
+
171
+ 1. Fork the repository
172
+ 2. Create a feature branch (`git checkout -b feature/your-feature`)
173
+ 3. Commit your changes with clear messages
174
+ 4. Push to your fork
175
+ 5. Open a pull request
176
+
177
+
178
+ ### Live testing with MCP Inspector (requires a real token)
179
+
180
+ ```bash
181
+ GITHUB_TOKEN=...
182
+ npx @modelcontextprotocol/inspector
183
+ uv run github-mcp
184
+ ```
185
+
186
+ Then call `github_search_repositories` (q=`"mcp language:python"`) or `github_get_repo` (owner=`"modelcontextprotocol"`, repo=`"python-sdk"`) to verify auth,
187
+ pagination, and formatting end-to-end.
188
+
189
+
190
+ ## Upcoming Features
191
+
192
+ - **Projects v2**: Requires GitHub's GraphQL API (`/graphql`). Add a `graphql_client.py` alongside `client.py` and a new `tools/projects.py` module.
193
+ - **Actions**: Also REST-based but with many endpoints. Add `tools/actions.py` importing from `client.py`.
@@ -0,0 +1,144 @@
1
+ # github-mcp
2
+
3
+ An MCP (Model COntext Protocol) server that gives AI assistants direct access to GitHub. Exposing ~22 GitHub REST tools
4
+ covering repos, files, issues, pull requests, as well as searching.
5
+
6
+ ## Table of Contents
7
+
8
+ 1. [Features](#features)
9
+ 2. [Installation](#installation)
10
+ 3. [Usage]()
11
+ 4. [Contributing]()
12
+
13
+ ## Features
14
+
15
+ A single stdio MCP server (built on [FastMCP](https://github.com/modelcontextprotocol/python-sdk)) exposing **23 GitHub REST tools** grouped into four areas:
16
+
17
+ - **Repositories & files** — `github_list_repos`, `github_get_repo`, `github_list_branches`, `github_list_commits`, `github_get_file_contents`, `github_list_directory`, `github_create_or_update_file`, `github_create_branch`
18
+ - **Issues** — `github_list_issues`, `github_get_issue`, `github_create_issue`, `github_update_issue`, `github_add_issue_comment`
19
+ - **Pull requests** — `github_list_pull_requests`, `github_get_pull_request`, `github_create_pull_request`, `github_merge_pull_request`, `github_add_pr_comment`
20
+ - **Search** — `github_search_repositories`, `github_search_code`, `github_search_issues`, `github_search_users`, `github_search_commits`
21
+
22
+ Under the hood:
23
+
24
+ - **Async HTTP** via a shared, lazily-initialised `httpx.AsyncClient` against the pinned GitHub API version (`2022-11-28`).
25
+ - **Automatic pagination** — list endpoints follow the `Link: rel="next"` header up to a configurable item cap.
26
+ - **Typed inputs** — every tool validates its arguments with Pydantic models.
27
+ - **Actionable errors** — common GitHub failures (401, 403/rate-limit with reset time, 404, 409, 422, timeouts) are translated into clear, human-readable messages.
28
+ - **Flexible auth** — reads a fine-grained PAT from `GITHUB_TOKEN`, falling back to `GITHUB_PAT`.
29
+
30
+ ## Installation
31
+
32
+ ### Prerequisites
33
+
34
+ - `Python 3.12` or later
35
+ - Dependencies `mcp[cli]>=1.0.0`, `httpx>=0.27.0`, `pydantic>=2.0.0` (see [pyproject.toml](pyproject.toml)) (project uses `poetry` for dependency management)
36
+
37
+
38
+ ### Install from PyPi
39
+
40
+ ```bash
41
+ pip install github-mcp
42
+
43
+ # or using poetry
44
+ poetry add github-mcp
45
+ ```
46
+
47
+ ### Build from source
48
+
49
+ ```bash
50
+ git clone https://github.com/LWaetzig/github-mcp.git
51
+ cd github-mcp
52
+ pip install -e .
53
+ ```
54
+
55
+ ## Usage
56
+
57
+ - Detailed documentation about single tools can be found this [sphinx documentation]()
58
+
59
+ ### Prerequisites
60
+
61
+ #### Create a fine-grained Personal Access Token (PAT)
62
+
63
+ 1. Go to **GitHub -> Settings -> Developer settings -> Personal access tokens -> Fine-grained tokens** (direct link: <https://github.com/settings/tokens?type=beta>)
64
+ 2. Generate new token
65
+ 3. Set **Resource owner** and **Repository access** as appropriate
66
+ 4. Grant these **Repository permissions** (minimum for full read + write):
67
+
68
+ | Permission | Access level | Used by tools |
69
+ | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
70
+ | **Metadata** | Read-only | All tools |
71
+ | **Contents** | Read and write | `github_get_file_contents`, `github_list_directory`, `github_list_commits`, `github_create_or_update_file`, `github_create_branch` |
72
+ | **Issues** | Read and write | `github_list_issues`, `github_get_issue`, `github_create_issue`, `github_update_issue`, `github_add_issue_comment` |
73
+ | **Pull requests** | Read and write | `github_list_pull_requests`, `github_get_pull_request`, `github_create_pull_request`, `github_merge_pull_request`, `github_add_pr_comment` |
74
+
75
+ > **Read-only subset**: grant only **Read-only** access to Contents, Issues, Pull requests, and Metadata if you don't need write tools.
76
+
77
+
78
+ ```bash
79
+ export GITHUB_TOKEN=github_pat_...
80
+ ```
81
+
82
+ Or copy `.env.example` -> `.env` and fill in the token (load with `source .env`).
83
+
84
+
85
+ ### Integrating with Claude Desktop
86
+
87
+ Add the server to your Claude Desktop configuration:
88
+
89
+ | Platform | Path |
90
+ |---|---|
91
+ | macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
92
+ | Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
93
+
94
+ Add the `github` entry under `mcpServers`, replacing the path with the absolute path to your clone:
95
+
96
+ ```json
97
+ {
98
+ "mcpServers" : {
99
+ "github" : {
100
+ "command" : "python",
101
+ "args" : ["-m", "github-mcp"],
102
+ "env" : {
103
+ "GITHUB_TOKEN" : "github_pat_..."
104
+ }
105
+ }
106
+ }
107
+ }
108
+ ```
109
+
110
+ Restart Claude Desktop. You should see the github tools available int he tool picker.
111
+
112
+ ### Integration with Other MCP Clients
113
+
114
+ Any MCP client (e.g. Cline, GitHub Copilot, or custm tools) can use this server.
115
+ Configuration depends on your assistant, in most cases there is a `config` to change.
116
+
117
+
118
+ ## Contribution
119
+
120
+ Contributions are welcome! Please:
121
+
122
+ 1. Fork the repository
123
+ 2. Create a feature branch (`git checkout -b feature/your-feature`)
124
+ 3. Commit your changes with clear messages
125
+ 4. Push to your fork
126
+ 5. Open a pull request
127
+
128
+
129
+ ### Live testing with MCP Inspector (requires a real token)
130
+
131
+ ```bash
132
+ GITHUB_TOKEN=...
133
+ npx @modelcontextprotocol/inspector
134
+ uv run github-mcp
135
+ ```
136
+
137
+ Then call `github_search_repositories` (q=`"mcp language:python"`) or `github_get_repo` (owner=`"modelcontextprotocol"`, repo=`"python-sdk"`) to verify auth,
138
+ pagination, and formatting end-to-end.
139
+
140
+
141
+ ## Upcoming Features
142
+
143
+ - **Projects v2**: Requires GitHub's GraphQL API (`/graphql`). Add a `graphql_client.py` alongside `client.py` and a new `tools/projects.py` module.
144
+ - **Actions**: Also REST-based but with many endpoints. Add `tools/actions.py` importing from `client.py`.
@@ -0,0 +1,73 @@
1
+ [project]
2
+ name = "github-mcp"
3
+ version = "v1.1.0"
4
+ description = "Local GitHub MCP server exposing GitHub REST API via FastMCP stdio transport"
5
+ requires-python = ">=3.12"
6
+ readme = "README.md"
7
+ license = {file = "LICENSE"}
8
+ authors = [ { name = "Lucas Waetzig", email = "development@waetzig.net" } ]
9
+ keywords = ["github", "mcp", "fastmcp", "stdio", "rest api", "search"]
10
+ classifiers = [
11
+ "Development Status :: 5 - Production/Stable",
12
+ "Intended Audience :: Developers",
13
+ "Intended Audience :: Science/Research",
14
+ "License :: OSI Approved :: MIT License",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Topic :: Scientific/Engineering",
20
+ "Topic :: Software Development :: Libraries",
21
+ ]
22
+
23
+ dependencies = [
24
+ "mcp[cli]>=1.0.0",
25
+ "httpx (>=0.28.1,<0.29.0)",
26
+ "pydantic (>=2.13.4,<3.0.0)",
27
+ ]
28
+
29
+ [dependency-groups]
30
+ dev = [
31
+ "pytest>=8.0",
32
+ "pytest-asyncio>=0.24",
33
+ "pytest-cov>=4.0.0",
34
+ "ruff (>=0.15.12,<0.16.0)",
35
+ "mypy (>=2.0.0,<3.0.0)",
36
+ ]
37
+ docs = [
38
+ "sphinx (>=9.1.0,<10.0.0)",
39
+ "sphinx-rtd-theme (>=3.1.0,<4.0.0)"
40
+ ]
41
+
42
+ [project.urls]
43
+ Homepage = "https://github.com/LWaetzig/github-mcp"
44
+ Repository = "https://github.com/LWaetzig/github-mcp"
45
+ Issues = "https://github.com/LWaetzig/github-mcp/issues"
46
+ Documentation = "https://personal-public-packages.gitlab.io/github-mcp"
47
+
48
+ [project.scripts]
49
+ github-query-mcp = "github_mcp.server:main"
50
+
51
+ [build-system]
52
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
53
+ build-backend = "poetry.core.masonry.api"
54
+
55
+ [tool.pytest.ini_options]
56
+ asyncio_mode = "auto"
57
+ pythonpath = ["src"]
58
+ addopts = "--cov=src --cov-report=term-missing --cov-fail-under=90"
59
+
60
+ [tool.ruff]
61
+ line-length = 88
62
+ target-version = "py312"
63
+ src = ["src", "tests"]
64
+
65
+ [tool.mypy]
66
+ python_version = "3.12"
67
+ mypy_path = "src"
68
+ files = ["src", "tests"]
69
+ pretty = true
70
+ show_error_codes = true
71
+ warn_unused_configs = true
72
+ check_untyped_defs = true
73
+ ignore_missing_imports = true
@@ -0,0 +1,3 @@
1
+ """GitHub MCP Server — exposes GitHub REST API via FastMCP stdio transport."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from mcp.server.fastmcp import FastMCP
2
+
3
+ mcp = FastMCP("github_mcp")
@@ -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}"