codeasier-gitcode-mcp 0.3.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.
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.5
2
+ Name: codeasier-gitcode-mcp
3
+ Version: 0.3.0
4
+ Summary: GitCode repository, code publishing, issue, and pull request tools for MCP clients
5
+ Project-URL: Repository, https://github.com/codeasier/gitcode-cli
6
+ Project-URL: Documentation, https://github.com/codeasier/gitcode-cli/tree/main/docs/gitcode
7
+ Author: Codeasier
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.11
11
+ Requires-Dist: anyio<5,>=4.9
12
+ Requires-Dist: cryptography<49,>=44
13
+ Requires-Dist: httpx<1,>=0.28.1
14
+ Requires-Dist: mcp==2.3.0
15
+ Requires-Dist: pydantic<3,>=2.12
16
+ Requires-Dist: pygitcode==0.1.7
17
+ Requires-Dist: uvicorn<1,>=0.31.1
18
+ Provides-Extra: dev
19
+ Requires-Dist: build<2,>=1.2; extra == 'dev'
20
+ Requires-Dist: packaging<26,>=24; extra == 'dev'
21
+ Requires-Dist: pytest<10,>=8.3; extra == 'dev'
22
+ Requires-Dist: ruff<1,>=0.11; extra == 'dev'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Codeasier GitCode MCP
26
+
27
+ An independently installable MCP server for GitCode repositories, file publishing,
28
+ issues and pull requests. It reuses `pygitcode` services and supports stdio and Streamable HTTP.
29
+ Public HTTPS deployments include a GitCode OAuth broker for connecting ChatGPT
30
+ directly by Server URL.
31
+
32
+ Requires Python 3.11 or later. From a checkout of `codeasier/gitcode-cli`:
33
+
34
+ ```sh
35
+ python -m pip install ./packages/gitcode-mcp
36
+ gitcode-mcp --help
37
+ python -m gitcode_mcp.smoke
38
+ ```
39
+
40
+ For local stdio or controlled static-bearer HTTP clients, supply `GITCODE_TOKEN`
41
+ (or `GC_TOKEN`) through the process environment or your secret manager. This is the
42
+ default `GITCODE_MCP_AUTH_MODE=bearer`. Set `GITCODE_MCP_READ_ONLY=true` to expose only read tools and
43
+ `GITCODE_MCP_ALLOWED_REPOS=owner/repository,owner/other` to constrain repository
44
+ access. Tokens are never MCP tool arguments.
45
+
46
+ For public HTTP, set `GITCODE_MCP_AUTH_MODE=oauth` and follow the
47
+ [OAuth setup guide](https://github.com/codeasier/gitcode-cli/blob/main/docs/gitcode/oauth.md).
48
+ Configure a GitCode OAuth application, a separate preregistered MCP client, exact
49
+ HTTPS callbacks, and persistent encrypted SQLite state. OAuth mode rejects PAT
50
+ and static HTTP bearer configuration; each authorized connection uses its own
51
+ GitCode identity and receives separate MCP access tokens. It supports PKCE,
52
+ explicit consent, refresh and revocation, with a fixed authorization lifetime.
53
+ The environment-file and Compose examples are in `deploy/gitcode-mcp`.
54
+
55
+ The server exposes 31 tools: 19 reads and 12 writes. `gitcode_create_file`,
56
+ `gitcode_update_file` and `gitcode_delete_file` publish a single file change to an
57
+ explicit remote branch using GitCode's Contents API. Updates and deletions require
58
+ the current file Blob SHA. Each call creates a separate commit; there is no atomic
59
+ multi-file commit or force-ref operation. See the
60
+ [code publishing guide](https://github.com/codeasier/gitcode-cli/blob/main/docs/gitcode/code-publishing.md)
61
+ for limits, verification and the Issue-to-PR workflow.
62
+
63
+ These API writes use the connection's GitCode authorization. OAuth connections
64
+ with `gitcode:write` and the required upstream permissions need no additional Git
65
+ credentials for file publishing. The server's read-only mode and repository
66
+ allowlist still apply. After upgrading the runtime, restart it and refresh the
67
+ client's tool metadata. Existing write grants cover these tools; an existing
68
+ read-only grant needs a new authorization to obtain write scope.
69
+
70
+ The built-in smoke command checks stdio. Automated OAuth tests use mocked GitCode
71
+ responses; verify the final HTTPS authorization flow and a real ChatGPT read before
72
+ considering a deployment connected.
73
+
74
+ The separate `gitcode-clone OWNER/REPO DESTINATION` command clones into the machine
75
+ where it is executed. A remote MCP connection does not share its filesystem with
76
+ dot or Codex. Run this helper in the actual coding environment, using an existing
77
+ Git credential helper, SSH, or the documented temporary PAT authentication.
78
+ The MCP server does not execute a shell or run project tests. Native Git operations
79
+ and test execution remain tasks for an actual coding environment.
80
+
81
+ See the repository's [setup and operation guide](https://github.com/codeasier/gitcode-cli/tree/main/docs/gitcode)
82
+ for local plugin installation, direct HTTPS/OAuth connection, the optional private
83
+ tunnel route and the Issue-to-PR workflow. This source package is not assumed to
84
+ be published on PyPI.
85
+
86
+ ## Migration provenance and compatibility
87
+
88
+ This package was imported from `codeasier/codex-codeasier` at
89
+ `f93b67bb7048e556b44322d48664522f32651920` (PR #8, subsequently merged as
90
+ `27b542521c8483b5cf051ae001e791e08e92bb40` with the same tree).
91
+ [`MIGRATION_SOURCE.json`](MIGRATION_SOURCE.json) records the original file mapping
92
+ and blob hashes; [`LICENSE`](LICENSE) retains the original MIT copyright notice.
93
+ The original regression tests preserve that baseline. The CLI package remains
94
+ separately versioned: this source now pins the published `pygitcode==0.1.7`, rather
95
+ than implicitly importing a sibling checkout. The MCP version remains `0.3.0`;
96
+ this dependency change does not publish or deploy an MCP release.
97
+
98
+ The existing file-read/create/update/delete tools delegate to the installed
99
+ `FileService`. MCP still owns its stricter path policy (including rejection of
100
+ literal `?`, `#` and `%`), canonical Base64 and size limits, explicit branch and
101
+ expected Blob SHA requirements, authorization, and normalized results. The
102
+ service receives decoded paths and quotes them exactly once, then uses MCP's
103
+ bounded bearer-only transport. No tool, schema, retry, automatic SHA refresh or
104
+ multi-file atomicity is added.
105
+
106
+ The existing `gitcode_get_repository` and `gitcode_get_clone_info` tools also
107
+ delegate their single metadata read to the installed `RepoService.get`. MCP
108
+ retains repository validation and allowlists, bearer-only transport, response
109
+ redaction, and credential-free clone URLs. This does not add tools or consume
110
+ unreleased CLI service methods.
111
+
112
+ Normal tests exercise this published dependency. A separate artifact matrix
113
+ installs the actual CLI wheel and sdist on Python 3.11–3.13, verifies their hashes
114
+ and installed origin, and runs both `tests/` and `tests_source/` in isolation.
115
+ Separately,
116
+ `gitcode-mcp-services.yml` installs the CLI checkout with `--no-deps`, verifies all
117
+ installed client/service hashes, and explicitly runs `tests_source/` and
118
+ `tests_checkout/` alongside the full MCP suite. The latter directory tests
119
+ unreleased repository branch/tree/commit primitives, Issue/PR single-page reads
120
+ and the raw structured-diff envelope directly with MCP's transport, not production
121
+ tool delegation. The Issue/PR primitives make one request and leave pagination,
122
+ shape validation and result envelopes to consumers. Existing eager comments,
123
+ files collection and text diff methods are unchanged. The checkout-only tests
124
+ are excluded from normal pinned tests and the published `0.1.7` artifact matrix.
125
+ Production consumption requires
126
+ a separately authorized CLI release, real artifact validation and a subsequent
127
+ consumer change. That forward-compatibility probe does not change the exact
128
+ production pin or authorize consuming unreleased services. Migration acceptance
129
+ keeps the immutable legacy MCP `0.3.0` / `pygitcode==0.1.6` installation for seed
130
+ and rollback; candidate checks require `pygitcode==0.1.7` even though its MCP
131
+ version is also `0.3.0`.
132
+
133
+ See the [migration and rollback guide](../../docs/gitcode/migration.md) before
134
+ upgrading an existing OAuth deployment. Repository migration does not authorize
135
+ a production switch, change the state schema or encryption key, or require new
136
+ user grants. A destination CI pass is required before switching a downstream
137
+ bridge to its exact commit or artifact.
138
+
139
+ ## Independent release preparation
140
+
141
+ See the [release guide](../../docs/gitcode/releases.md) for `mcp-vX.Y.Z` tags,
142
+ artifact gates, and the separately authorized PyPI setup. Manual release-workflow
143
+ runs validate only; they cannot publish. Merging this workflow does not publish a
144
+ package, change downstream pins, or deploy a server.
@@ -0,0 +1,20 @@
1
+ gitcode_mcp/__init__.py,sha256=gmr9uxJQzo5LAqvZ2rrEfktoSH1dvdDLssmEGVliZRs,61
2
+ gitcode_mcp/__main__.py,sha256=RHXhSG8tbRjuqHt74veK_d_rowgMVVnibg1Rp1YSW8o,3194
3
+ gitcode_mcp/api.py,sha256=qb6aOK7ynqeqTj3TWs-HYEtHo_TL_I0yjbtFu0bdfm8,11923
4
+ gitcode_mcp/askpass.py,sha256=Ge_HsbuLIygJMgONzobKt8xi8orfGc0fXTjIsgMbJC8,1064
5
+ gitcode_mcp/clone.py,sha256=bkUt1yrMfn2zxfSIRvu-4SGz8LS9tg1Nu8qAUqHttrw,8371
6
+ gitcode_mcp/config.py,sha256=eW71isbanLCUq9tW-XyBJWvecCtwN7HcexaU5Bbwhtg,6722
7
+ gitcode_mcp/file_writes.py,sha256=IQZSkvEaQuewbjBTDXtMFNwUaIHFT-wOwhUFkdQdoqI,5221
8
+ gitcode_mcp/oauth.py,sha256=aVhhfpkkasMGtqj7-vTr5tyQJVCSTw1UlSAD8gwZljY,25839
9
+ gitcode_mcp/oauth_config.py,sha256=_foZUecx8DGntoJx4OFV48LJICPT8_RpwOZ5zSNjd70,5161
10
+ gitcode_mcp/oauth_http.py,sha256=b-6JQoM0xWfMkc5_cKytdBaqMjGt4nlO9r_2bU_vP00,6525
11
+ gitcode_mcp/oauth_store.py,sha256=7GBLcmzSW8jWU5DWYAyKu4UMcX7ocZPmhMkqXgZVyco,17773
12
+ gitcode_mcp/oauth_upstream.py,sha256=-MefIx6oAd96CgjVks0NPjnXlp5EYvcVAIE5lDtAWo0,12482
13
+ gitcode_mcp/server.py,sha256=wSNp-QnKFVT7GTpqrysIdCm34Dhguwt-E-C0AEVg96Q,8876
14
+ gitcode_mcp/smoke.py,sha256=l3Hkr05oa6aIAhGL0Il3iwuP0zv9Co22dK4ujIWo7Ck,2361
15
+ gitcode_mcp/tools.py,sha256=RwjwLhzXGzhWokeb_7ONrJ4S_fJjyV9aeU5GsJaPnx4,26515
16
+ codeasier_gitcode_mcp-0.3.0.dist-info/METADATA,sha256=-GH_sbbiYvSZemSQyKMLx7hKd1Xj_cMX5MPMxht0u3Y,8020
17
+ codeasier_gitcode_mcp-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
18
+ codeasier_gitcode_mcp-0.3.0.dist-info/entry_points.txt,sha256=iwlEmxnm9QXgAnzxGVUzRWAE7QGZoCplJEylj-_baQA,97
19
+ codeasier_gitcode_mcp-0.3.0.dist-info/licenses/LICENSE,sha256=Kwrz_Uy-yqWH3TZFg0POzY_IFs9OU_byhVCoXhWt5W0,1066
20
+ codeasier_gitcode_mcp-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ gitcode-clone = gitcode_mcp.clone:main
3
+ gitcode-mcp = gitcode_mcp.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 codeasier
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,3 @@
1
+ """Codeasier's GitCode MCP server."""
2
+
3
+ __version__ = "0.3.0"
@@ -0,0 +1,83 @@
1
+ """Console entry point. Stdout is reserved exclusively for the stdio protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import sys
8
+
9
+ import anyio
10
+ import uvicorn
11
+ from mcp.server.stdio import stdio_server
12
+
13
+ from . import __version__
14
+ from .api import GitCodeAPI
15
+ from .config import ConfigurationError, Settings
16
+ from .server import create_http_app, create_server
17
+
18
+
19
+ def main(argv: list[str] | None = None) -> int:
20
+ parser = argparse.ArgumentParser(
21
+ description="GitCode MCP server (credentials from environment)"
22
+ )
23
+ parser.add_argument("--version", action="version", version=__version__)
24
+ parser.add_argument("--transport", choices=("stdio", "streamable-http"), default="stdio")
25
+ parser.add_argument("--host", default="127.0.0.1", help="HTTP bind address")
26
+ parser.add_argument("--port", type=int, default=8765, help="HTTP port")
27
+ parser.add_argument("--read-only", action="store_true", help="Hide and reject mutation tools")
28
+ args = parser.parse_args(argv)
29
+ if not 1 <= args.port <= 65535:
30
+ parser.error("--port must be between 1 and 65535")
31
+ logging.basicConfig(
32
+ level=logging.WARNING, stream=sys.stderr, format="%(levelname)s %(message)s"
33
+ )
34
+ try:
35
+ settings = Settings.from_env()
36
+ if args.read_only:
37
+ from dataclasses import replace
38
+
39
+ settings = replace(settings, read_only=True)
40
+ if settings.oauth is not None and args.transport != "streamable-http":
41
+ raise ConfigurationError("OAuth mode requires --transport streamable-http.")
42
+ oauth_provider = None
43
+ if settings.oauth is not None:
44
+ from .oauth import GitCodeOAuthProvider
45
+ from .oauth_store import OAuthStoreError
46
+
47
+ try:
48
+ oauth_provider = GitCodeOAuthProvider(settings)
49
+ except OAuthStoreError:
50
+ raise ConfigurationError(
51
+ "Cannot open OAuth storage. Check the database path, permissions and persistent encryption key."
52
+ ) from None
53
+ api = GitCodeAPI(
54
+ settings.token, timeout=settings.timeout, max_response_bytes=settings.max_response_bytes
55
+ )
56
+ try:
57
+ server = create_server(settings, api=api, oauth_provider=oauth_provider)
58
+ if args.transport == "stdio":
59
+
60
+ async def serve() -> None:
61
+ async with stdio_server() as (reader, writer):
62
+ await server.run(reader, writer, server.create_initialization_options())
63
+
64
+ anyio.run(serve)
65
+ else:
66
+ app = create_http_app(server, settings, args.host, oauth_provider=oauth_provider)
67
+ uvicorn.run(
68
+ app, host=args.host, port=args.port, log_level="warning", access_log=False
69
+ )
70
+ finally:
71
+ api.close()
72
+ if oauth_provider is not None:
73
+ anyio.run(oauth_provider.aclose)
74
+ except ConfigurationError as exc:
75
+ print(f"Configuration error: {exc}", file=sys.stderr)
76
+ return 2
77
+ except KeyboardInterrupt:
78
+ return 0
79
+ return 0
80
+
81
+
82
+ if __name__ == "__main__":
83
+ raise SystemExit(main())
gitcode_mcp/api.py ADDED
@@ -0,0 +1,285 @@
1
+ """Bounded, credential-safe HTTP adapter for pygitcode's service layer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json as json_module
6
+ from typing import Any, Literal
7
+ from urllib.parse import quote, unquote
8
+
9
+ import httpx
10
+ from gitcode_cli.client import GitCodeClient
11
+ from gitcode_cli.services.files import FileService
12
+ from gitcode_cli.services.issues import IssueService
13
+ from gitcode_cli.services.pulls import PullRequestService
14
+ from gitcode_cli.services.repos import RepoService
15
+
16
+ API_BASE_URL = "https://api.gitcode.com/api/v5/"
17
+
18
+
19
+ class GitCodeError(Exception):
20
+ """An error safe to return to an MCP caller without upstream response text."""
21
+
22
+ def __init__(
23
+ self,
24
+ code: str,
25
+ message: str,
26
+ *,
27
+ status_code: int | None = None,
28
+ retry_after: int | None = None,
29
+ operation_may_have_completed: bool | None = None,
30
+ ) -> None:
31
+ if operation_may_have_completed:
32
+ message += (
33
+ " The write may have completed. Verify remote state before retrying;"
34
+ " do not automatically retry this operation."
35
+ )
36
+ super().__init__(message)
37
+ self.code = code
38
+ self.message = message
39
+ self.status_code = status_code
40
+ self.retry_after = retry_after
41
+ self.operation_may_have_completed = operation_may_have_completed
42
+
43
+ def to_dict(self) -> dict[str, Any]:
44
+ result: dict[str, Any] = {"code": self.code, "message": self.message}
45
+ if self.status_code is not None:
46
+ result["status_code"] = self.status_code
47
+ if self.retry_after is not None:
48
+ result["retry_after"] = self.retry_after
49
+ if self.operation_may_have_completed is not None:
50
+ result["operation_may_have_completed"] = self.operation_may_have_completed
51
+ return result
52
+
53
+
54
+ def segment(value: str) -> str:
55
+ """Encode a validated resource name as exactly one URL path segment."""
56
+ return quote(value, safe="")
57
+
58
+
59
+ class GitCodeAPI(GitCodeClient):
60
+ """Reuse pygitcode services, replacing its query-token HTTP implementation.
61
+
62
+ This client has one fixed upstream host. Redirects and environment proxies
63
+ are disabled; no upstream error body, URL, or exception text reaches tools.
64
+ Requests are never retried automatically, particularly after a write.
65
+ ``transport`` is an in-process test seam, not a configurable upstream URL.
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ token: str,
71
+ *,
72
+ timeout: float = 30.0,
73
+ max_response_bytes: int = 2_000_000,
74
+ transport: httpx.BaseTransport | None = None,
75
+ ) -> None:
76
+ if token and any(character.isspace() for character in token):
77
+ raise GitCodeError(
78
+ "invalid_configuration", "The GitCode token cannot contain whitespace."
79
+ )
80
+ if timeout <= 0 or max_response_bytes < 1:
81
+ raise GitCodeError("invalid_configuration", "HTTP limits must be positive.")
82
+ # Do not call the upstream constructor, which creates a second client.
83
+ self.token = token
84
+ self.base_url = API_BASE_URL
85
+ self.max_response_bytes = max_response_bytes
86
+ self._client = httpx.Client(
87
+ timeout=timeout,
88
+ follow_redirects=False,
89
+ trust_env=False,
90
+ transport=transport,
91
+ headers={
92
+ "User-Agent": "codeasier-gitcode-mcp",
93
+ **({"Authorization": f"Bearer {token}"} if token else {}),
94
+ },
95
+ )
96
+ self.issues = IssueService(self)
97
+ self.pulls = PullRequestService(self)
98
+ self.files = FileService(self)
99
+ self.repos = RepoService(self)
100
+
101
+ def close(self) -> None:
102
+ self._client.close()
103
+
104
+ def __enter__(self) -> GitCodeAPI:
105
+ return self
106
+
107
+ def __exit__(self, *_: Any) -> None:
108
+ self.close()
109
+
110
+ def _redact(self, value: Any) -> Any:
111
+ if not self.token:
112
+ return value
113
+ if isinstance(value, str):
114
+ return value.replace(self.token, "[REDACTED]")
115
+ if isinstance(value, list):
116
+ return [self._redact(item) for item in value]
117
+ if isinstance(value, dict):
118
+ return {self._redact(key): self._redact(item) for key, item in value.items()}
119
+ return value
120
+
121
+ @staticmethod
122
+ def _status_error(response: httpx.Response, *, mutation: bool = False) -> GitCodeError:
123
+ status = response.status_code
124
+ errors = {
125
+ 401: ("authentication_failed", "GitCode rejected the configured credential."),
126
+ 403: ("permission_denied", "The GitCode credential cannot perform this operation."),
127
+ 404: ("not_found", "The GitCode resource was not found or is not accessible."),
128
+ 409: (
129
+ "conflict",
130
+ "GitCode reported a conflict; read the current resource before retrying.",
131
+ ),
132
+ 422: (
133
+ "upstream_validation",
134
+ "GitCode rejected the operation's parameters or current state.",
135
+ ),
136
+ 429: (
137
+ "rate_limited",
138
+ "GitCode's rate limit was reached; retry after the indicated delay.",
139
+ ),
140
+ }
141
+ code, message = errors.get(
142
+ status, ("upstream_error", "GitCode returned an unsuccessful response.")
143
+ )
144
+ retry_after = None
145
+ header = response.headers.get("Retry-After", "")
146
+ if status == 429 and header.isascii() and header.isdigit() and len(header) <= 6:
147
+ retry_after = min(int(header), 86400)
148
+ return GitCodeError(
149
+ code,
150
+ message,
151
+ status_code=status,
152
+ retry_after=retry_after,
153
+ operation_may_have_completed=True if mutation and 500 <= status < 600 else None,
154
+ )
155
+
156
+ def request(
157
+ self,
158
+ method: str,
159
+ path: str,
160
+ *,
161
+ params: dict[str, Any] | None = None,
162
+ json: dict[str, Any] | None = None,
163
+ accept: str = "application/json",
164
+ response_format: Literal["json", "text"] = "json",
165
+ ) -> Any:
166
+ """Issue a bounded request using pygitcode's public request signature."""
167
+ mutation = method.upper() in {"POST", "PUT", "PATCH", "DELETE"}
168
+ if not self.token:
169
+ raise GitCodeError(
170
+ "configuration_error", "Set GITCODE_TOKEN or GC_TOKEN before calling GitCode tools."
171
+ )
172
+ decoded = unquote(path)
173
+ if (
174
+ not path.startswith("/repos/")
175
+ or any(part in {".", ".."} for part in decoded.split("/"))
176
+ or any(character in decoded for character in "\\?#\r\n")
177
+ or "://" in decoded
178
+ ):
179
+ raise GitCodeError(
180
+ "invalid_path", "Only validated GitCode repository API paths are allowed."
181
+ )
182
+ if params and any(
183
+ key.casefold() in {"access_token", "token", "authorization"} for key in params
184
+ ):
185
+ raise GitCodeError(
186
+ "invalid_arguments", "Credentials cannot be supplied in API query parameters."
187
+ )
188
+ url = API_BASE_URL + path.lstrip("/")
189
+ query = {key: value for key, value in (params or {}).items() if value is not None}
190
+ try:
191
+ with self._client.stream(
192
+ method, url, params=query, json=json, headers={"Accept": accept}
193
+ ) as response:
194
+ if 300 <= response.status_code < 400:
195
+ raise GitCodeError(
196
+ "upstream_redirect",
197
+ "GitCode returned a redirect; credentials were not forwarded.",
198
+ status_code=response.status_code,
199
+ operation_may_have_completed=True if mutation else None,
200
+ )
201
+ if response.status_code >= 400:
202
+ raise self._status_error(response, mutation=mutation)
203
+ content = bytearray()
204
+ for chunk in response.iter_bytes(
205
+ chunk_size=min(65_536, self.max_response_bytes + 1)
206
+ ):
207
+ content.extend(chunk)
208
+ if len(content) > self.max_response_bytes:
209
+ raise GitCodeError(
210
+ "response_too_large",
211
+ (
212
+ "GitCode's write response exceeds the configured size limit."
213
+ if mutation
214
+ else "GitCode's response exceeds the configured size limit; request a smaller page or file. For unpaged PR data, use git diff in a local checkout."
215
+ ),
216
+ operation_may_have_completed=True if mutation else None,
217
+ )
218
+ except httpx.TimeoutException:
219
+ raise GitCodeError(
220
+ "timeout",
221
+ "GitCode did not respond in time.",
222
+ operation_may_have_completed=True if mutation else None,
223
+ ) from None
224
+ except httpx.HTTPError:
225
+ raise GitCodeError(
226
+ "network_error",
227
+ "The GitCode request failed.",
228
+ operation_may_have_completed=True if mutation else None,
229
+ ) from None
230
+ if not content:
231
+ return None
232
+ try:
233
+ if response_format == "text":
234
+ return self._redact(content.decode("utf-8"))
235
+ return self._redact(json_module.loads(content))
236
+ except (ValueError, UnicodeError):
237
+ raise GitCodeError(
238
+ "invalid_response",
239
+ "GitCode returned an invalid response format.",
240
+ operation_may_have_completed=True if mutation else None,
241
+ ) from None
242
+
243
+ def page(self, path: str, *, page: int, per_page: int, **params: Any) -> dict[str, Any]:
244
+ """Fetch exactly one page. A full page conservatively offers a next page."""
245
+ items = self.get(path, params={**params, "page": page, "per_page": per_page})
246
+ return self.page_result(items, page=page, per_page=per_page)
247
+
248
+ @staticmethod
249
+ def page_result(items: Any, *, page: int, per_page: int) -> dict[str, Any]:
250
+ if not isinstance(items, list):
251
+ raise GitCodeError("invalid_response", "GitCode did not return the expected list.")
252
+ if len(items) > per_page:
253
+ raise GitCodeError(
254
+ "invalid_response", "GitCode returned more items than the requested page size."
255
+ )
256
+ return {
257
+ "data": items,
258
+ "page": page,
259
+ "per_page": per_page,
260
+ "next_page": page + 1 if len(items) == per_page else None,
261
+ "pagination_mode": "upstream",
262
+ "pagination_note": "A full page may have a next page; that next page can be empty.",
263
+ }
264
+
265
+ @staticmethod
266
+ def collection_page_result(items: Any, *, page: int, per_page: int) -> dict[str, Any]:
267
+ """Slice a bounded response from an endpoint without documented paging.
268
+
269
+ This does not call pygitcode's eager pagination or assume the upstream
270
+ accepts page/per_page. Every tool invocation fetches the collection
271
+ again; a changing resource is not a stable multi-page snapshot.
272
+ """
273
+ if not isinstance(items, list):
274
+ raise GitCodeError("invalid_response", "GitCode did not return the expected list.")
275
+ start = (page - 1) * per_page
276
+ end = start + per_page
277
+ return {
278
+ "data": items[start:end],
279
+ "page": page,
280
+ "per_page": per_page,
281
+ "next_page": page + 1 if end < len(items) else None,
282
+ "pagination_mode": "client",
283
+ "total_items": len(items),
284
+ "pagination_note": "GitCode does not document upstream pagination for this endpoint. One size-bounded response is sliced locally; each call fetches it again, so pages are not a stable snapshot.",
285
+ }
gitcode_mcp/askpass.py ADDED
@@ -0,0 +1,40 @@
1
+ """Short-lived Git credential prompt handler; never invoke through MCP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from urllib.parse import urlsplit
8
+
9
+
10
+ def answer(prompt: str, token: str, username: str) -> str | None:
11
+ """Only supply credentials for an HTTPS GitCode prompt, never a redirected host."""
12
+ if "'" not in prompt:
13
+ return None
14
+ try:
15
+ url = urlsplit(prompt.split("'", 2)[1])
16
+ if url.scheme != "https" or url.hostname != "gitcode.com" or url.port not in (None, 443):
17
+ return None
18
+ except ValueError:
19
+ return None
20
+ if prompt.startswith("Username for "):
21
+ return username
22
+ if prompt.startswith("Password for "):
23
+ return token
24
+ return None
25
+
26
+
27
+ def main() -> int:
28
+ value = answer(
29
+ sys.argv[1] if len(sys.argv) == 2 else "",
30
+ os.environ.get("GITCODE_CLONE_TOKEN", ""),
31
+ os.environ.get("GITCODE_CLONE_USERNAME", ""),
32
+ )
33
+ if not value:
34
+ return 1
35
+ print(value)
36
+ return 0
37
+
38
+
39
+ if __name__ == "__main__":
40
+ raise SystemExit(main())