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.
- codeasier_gitcode_mcp-0.3.0.dist-info/METADATA +144 -0
- codeasier_gitcode_mcp-0.3.0.dist-info/RECORD +20 -0
- codeasier_gitcode_mcp-0.3.0.dist-info/WHEEL +4 -0
- codeasier_gitcode_mcp-0.3.0.dist-info/entry_points.txt +3 -0
- codeasier_gitcode_mcp-0.3.0.dist-info/licenses/LICENSE +21 -0
- gitcode_mcp/__init__.py +3 -0
- gitcode_mcp/__main__.py +83 -0
- gitcode_mcp/api.py +285 -0
- gitcode_mcp/askpass.py +40 -0
- gitcode_mcp/clone.py +208 -0
- gitcode_mcp/config.py +170 -0
- gitcode_mcp/file_writes.py +132 -0
- gitcode_mcp/oauth.py +636 -0
- gitcode_mcp/oauth_config.py +135 -0
- gitcode_mcp/oauth_http.py +163 -0
- gitcode_mcp/oauth_store.py +431 -0
- gitcode_mcp/oauth_upstream.py +320 -0
- gitcode_mcp/server.py +218 -0
- gitcode_mcp/smoke.py +64 -0
- gitcode_mcp/tools.py +689 -0
gitcode_mcp/tools.py
ADDED
|
@@ -0,0 +1,689 @@
|
|
|
1
|
+
"""Focused GitCode tools with input schemas and enforced execution policies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Annotated, Any, Literal
|
|
8
|
+
|
|
9
|
+
from mcp.types import Tool, ToolAnnotations
|
|
10
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
|
|
11
|
+
|
|
12
|
+
from .api import GitCodeAPI, GitCodeError, segment
|
|
13
|
+
from .file_writes import (
|
|
14
|
+
FILE_WRITE_METHODS,
|
|
15
|
+
MAX_ENCODED_FILE_CHARS,
|
|
16
|
+
MAX_MESSAGE_BYTES,
|
|
17
|
+
encode_file_content,
|
|
18
|
+
utf8_bytes,
|
|
19
|
+
validate_commit_message,
|
|
20
|
+
validate_write_branch,
|
|
21
|
+
write_file,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
PositiveNumber = Annotated[int, Field(ge=1)]
|
|
25
|
+
Name = Annotated[str, Field(min_length=1, max_length=255, pattern=r"^[A-Za-z0-9_][A-Za-z0-9_.-]*$")]
|
|
26
|
+
Text = Annotated[str, Field(max_length=65_536)]
|
|
27
|
+
Title = Annotated[str, Field(min_length=1, max_length=1024)]
|
|
28
|
+
Reference = Annotated[str, Field(min_length=1, max_length=1024)]
|
|
29
|
+
Labels = Annotated[list[Annotated[str, Field(min_length=1, max_length=100)]], Field(max_length=100)]
|
|
30
|
+
BlobSHA = Annotated[str, Field(min_length=40, max_length=40, pattern=r"^[0-9a-fA-F]{40}$")]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _safe_reference(value: str) -> str:
|
|
34
|
+
if (
|
|
35
|
+
any(character.isspace() or ord(character) < 32 for character in value)
|
|
36
|
+
or any(character in value for character in "\\%?#")
|
|
37
|
+
or any(part in {".", "..", ""} for part in value.split("/"))
|
|
38
|
+
):
|
|
39
|
+
raise ValueError(
|
|
40
|
+
"Use a literal branch, tag, or commit without path traversal or URL encoding."
|
|
41
|
+
)
|
|
42
|
+
return value
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _safe_file_path(value: str) -> str:
|
|
46
|
+
if (
|
|
47
|
+
value.startswith("/")
|
|
48
|
+
or any(character in value for character in "\\%?#")
|
|
49
|
+
or any(ord(character) < 32 or ord(character) == 127 for character in value)
|
|
50
|
+
or any(part in {".", "..", ""} for part in value.split("/"))
|
|
51
|
+
):
|
|
52
|
+
raise ValueError("Use a relative repository file path without traversal or URL encoding.")
|
|
53
|
+
return value
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class RepoArgs(BaseModel):
|
|
57
|
+
model_config = ConfigDict(extra="forbid", strict=True)
|
|
58
|
+
owner: Name = Field(description="GitCode owner or organization path, for example Ascend.")
|
|
59
|
+
repo: Name = Field(description="GitCode repository path, without a URL or .git suffix.")
|
|
60
|
+
|
|
61
|
+
@field_validator("owner", "repo")
|
|
62
|
+
@classmethod
|
|
63
|
+
def validate_name(cls, value: str) -> str:
|
|
64
|
+
if ".." in value or value.endswith(".git"):
|
|
65
|
+
raise ValueError("Repository names cannot contain '..' or end with '.git'.")
|
|
66
|
+
return value
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class PageArgs(RepoArgs):
|
|
70
|
+
page: Annotated[int, Field(ge=1)] = 1
|
|
71
|
+
per_page: Annotated[int, Field(ge=1, le=100)] = 30
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class BranchArgs(RepoArgs):
|
|
75
|
+
branch: Reference
|
|
76
|
+
|
|
77
|
+
@field_validator("branch")
|
|
78
|
+
@classmethod
|
|
79
|
+
def validate_branch(cls, value: str) -> str:
|
|
80
|
+
return _safe_reference(value)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class FileArgs(RepoArgs):
|
|
84
|
+
path: Annotated[str, Field(min_length=1, max_length=4096)]
|
|
85
|
+
ref: Reference | None = None
|
|
86
|
+
|
|
87
|
+
@field_validator("path")
|
|
88
|
+
@classmethod
|
|
89
|
+
def validate_path(cls, value: str) -> str:
|
|
90
|
+
return _safe_file_path(value)
|
|
91
|
+
|
|
92
|
+
@field_validator("ref")
|
|
93
|
+
@classmethod
|
|
94
|
+
def validate_ref(cls, value: str | None) -> str | None:
|
|
95
|
+
return None if value is None else _safe_reference(value)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class TreeArgs(PageArgs):
|
|
99
|
+
sha: Reference = Field(description="Commit SHA, branch, or tag identifying the tree.")
|
|
100
|
+
recursive: bool = False
|
|
101
|
+
file_path: Annotated[str, Field(min_length=1, max_length=4096)] | None = None
|
|
102
|
+
|
|
103
|
+
@field_validator("sha")
|
|
104
|
+
@classmethod
|
|
105
|
+
def validate_ref(cls, value: str) -> str:
|
|
106
|
+
return _safe_reference(value)
|
|
107
|
+
|
|
108
|
+
@field_validator("file_path")
|
|
109
|
+
@classmethod
|
|
110
|
+
def validate_path(cls, value: str | None) -> str | None:
|
|
111
|
+
return None if value is None else _safe_file_path(value)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class CommitArgs(RepoArgs):
|
|
115
|
+
sha: Reference
|
|
116
|
+
|
|
117
|
+
@field_validator("sha")
|
|
118
|
+
@classmethod
|
|
119
|
+
def validate_ref(cls, value: str) -> str:
|
|
120
|
+
return _safe_reference(value)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class CommitsArgs(PageArgs):
|
|
124
|
+
sha: Reference | None = None
|
|
125
|
+
path: Annotated[str, Field(max_length=4096)] | None = None
|
|
126
|
+
|
|
127
|
+
@field_validator("sha")
|
|
128
|
+
@classmethod
|
|
129
|
+
def validate_ref(cls, value: str | None) -> str | None:
|
|
130
|
+
return None if value is None else _safe_reference(value)
|
|
131
|
+
|
|
132
|
+
@field_validator("path")
|
|
133
|
+
@classmethod
|
|
134
|
+
def validate_path(cls, value: str | None) -> str | None:
|
|
135
|
+
return None if value is None else _safe_file_path(value)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class CreateBranchArgs(RepoArgs):
|
|
139
|
+
branch_name: Reference
|
|
140
|
+
refs: Reference = Field(description="Existing branch, tag, or commit to branch from.")
|
|
141
|
+
description: Annotated[str, Field(max_length=4096)] | None = None
|
|
142
|
+
|
|
143
|
+
@field_validator("branch_name", "refs")
|
|
144
|
+
@classmethod
|
|
145
|
+
def validate_ref(cls, value: str) -> str:
|
|
146
|
+
return _safe_reference(value)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class FileWriteArgs(RepoArgs):
|
|
150
|
+
path: Annotated[str, Field(min_length=1, max_length=4096)] = Field(
|
|
151
|
+
description="Relative repository file path, not a local filesystem path."
|
|
152
|
+
)
|
|
153
|
+
branch: Reference = Field(
|
|
154
|
+
description="Explicit existing short branch name. Never defaults to the default branch."
|
|
155
|
+
)
|
|
156
|
+
message: Annotated[str, Field(min_length=1, max_length=MAX_MESSAGE_BYTES)] = Field(
|
|
157
|
+
description="Nonblank commit message, at most 4096 UTF-8 bytes."
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
@field_validator("path")
|
|
161
|
+
@classmethod
|
|
162
|
+
def validate_path(cls, value: str) -> str:
|
|
163
|
+
utf8_bytes(value, maximum=4096)
|
|
164
|
+
return _safe_file_path(value)
|
|
165
|
+
|
|
166
|
+
@field_validator("branch")
|
|
167
|
+
@classmethod
|
|
168
|
+
def validate_branch(cls, value: str) -> str:
|
|
169
|
+
return validate_write_branch(value)
|
|
170
|
+
|
|
171
|
+
@field_validator("message")
|
|
172
|
+
@classmethod
|
|
173
|
+
def validate_message(cls, value: str) -> str:
|
|
174
|
+
return validate_commit_message(value)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class CreateFileArgs(FileWriteArgs):
|
|
178
|
+
content: Annotated[str, Field(max_length=MAX_ENCODED_FILE_CHARS)] = Field(
|
|
179
|
+
description="Complete file content; at most 256 KiB of decoded bytes. Empty files are allowed."
|
|
180
|
+
)
|
|
181
|
+
encoding: Literal["utf-8", "base64"] = Field(
|
|
182
|
+
default="utf-8", description="UTF-8 text or canonical, padded Base64 without whitespace."
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
@model_validator(mode="after")
|
|
186
|
+
def validate_content(self) -> CreateFileArgs:
|
|
187
|
+
encode_file_content(self.content, self.encoding)
|
|
188
|
+
return self
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class UpdateFileArgs(CreateFileArgs):
|
|
192
|
+
sha: BlobSHA = Field(
|
|
193
|
+
description="Existing file Blob SHA from get_file_contents at this branch; not a commit SHA."
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
@field_validator("sha")
|
|
197
|
+
@classmethod
|
|
198
|
+
def normalize_sha(cls, value: str) -> str:
|
|
199
|
+
return value.lower()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class DeleteFileArgs(FileWriteArgs):
|
|
203
|
+
sha: BlobSHA = Field(
|
|
204
|
+
description="Existing file Blob SHA from get_file_contents at this branch; not a commit SHA."
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
@field_validator("sha")
|
|
208
|
+
@classmethod
|
|
209
|
+
def normalize_sha(cls, value: str) -> str:
|
|
210
|
+
return value.lower()
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class ListIssuesArgs(PageArgs):
|
|
214
|
+
state: Literal["open", "closed", "all"] = "open"
|
|
215
|
+
search: Annotated[str, Field(max_length=1024)] | None = None
|
|
216
|
+
labels: Labels | None = None
|
|
217
|
+
creator: Name | None = None
|
|
218
|
+
assignee: Annotated[str, Field(min_length=1, max_length=100)] | None = Field(
|
|
219
|
+
default=None,
|
|
220
|
+
description="GitCode issue assignee ID, not a GitHub-style username assumption.",
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class IssueArgs(RepoArgs):
|
|
225
|
+
issue_number: PositiveNumber
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class IssuePageArgs(PageArgs):
|
|
229
|
+
issue_number: PositiveNumber
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class CreateIssueArgs(RepoArgs):
|
|
233
|
+
title: Title
|
|
234
|
+
body: Text = ""
|
|
235
|
+
assignee: Name | None = Field(default=None, description="GitCode issue assignee username.")
|
|
236
|
+
labels: Labels | None = None
|
|
237
|
+
milestone: PositiveNumber | None = None
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class UpdateIssueArgs(IssueArgs):
|
|
241
|
+
title: Title = Field(
|
|
242
|
+
description="GitCode requires a title on updates; preserve the existing title when unchanged."
|
|
243
|
+
)
|
|
244
|
+
body: Text | None = None
|
|
245
|
+
state: Literal["close", "reopen"] | None = Field(
|
|
246
|
+
default=None,
|
|
247
|
+
description="GitCode update actions are close/reopen; list states are open/closed.",
|
|
248
|
+
)
|
|
249
|
+
assignee: Name | None = None
|
|
250
|
+
labels: Labels | None = None
|
|
251
|
+
milestone: PositiveNumber | None = None
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class IssueCommentArgs(IssueArgs):
|
|
255
|
+
body: Annotated[str, Field(min_length=1, max_length=65_536)]
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
class ListPullsArgs(PageArgs):
|
|
259
|
+
state: Literal["open", "closed", "merged", "locked", "all"] = "open"
|
|
260
|
+
base: Reference | None = None
|
|
261
|
+
author: Name | None = None
|
|
262
|
+
labels: Labels | None = None
|
|
263
|
+
|
|
264
|
+
@field_validator("base")
|
|
265
|
+
@classmethod
|
|
266
|
+
def validate_ref(cls, value: str | None) -> str | None:
|
|
267
|
+
return None if value is None else _safe_reference(value)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class PullArgs(RepoArgs):
|
|
271
|
+
pull_number: PositiveNumber
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
class PullPageArgs(PageArgs):
|
|
275
|
+
pull_number: PositiveNumber
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
class CreatePullArgs(RepoArgs):
|
|
279
|
+
title: Title
|
|
280
|
+
head: Reference = Field(
|
|
281
|
+
description="Source branch; use username:branch for a cross-repository PR."
|
|
282
|
+
)
|
|
283
|
+
base: Reference
|
|
284
|
+
body: Text = ""
|
|
285
|
+
draft: bool = False
|
|
286
|
+
fork_path: Annotated[str, Field(max_length=511)] | None = Field(
|
|
287
|
+
default=None, description="Required owner/repo source path for a cross-repository PR."
|
|
288
|
+
)
|
|
289
|
+
assignees: Annotated[list[Name], Field(max_length=100)] | None = Field(
|
|
290
|
+
default=None, description="GitCode PR reviewers, not issue assignees."
|
|
291
|
+
)
|
|
292
|
+
testers: Annotated[list[Name], Field(max_length=100)] | None = None
|
|
293
|
+
labels: Labels | None = None
|
|
294
|
+
milestone_number: PositiveNumber | None = None
|
|
295
|
+
issue_numbers: Annotated[list[PositiveNumber], Field(max_length=100)] = Field(
|
|
296
|
+
default_factory=list,
|
|
297
|
+
description="Linked issue numbers, mapped to GitCode inner_issue_nums.",
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
@field_validator("head", "base")
|
|
301
|
+
@classmethod
|
|
302
|
+
def validate_ref(cls, value: str) -> str:
|
|
303
|
+
return _safe_reference(value)
|
|
304
|
+
|
|
305
|
+
@model_validator(mode="after")
|
|
306
|
+
def check_fork(self) -> CreatePullArgs:
|
|
307
|
+
if ":" in self.head and not self.fork_path:
|
|
308
|
+
raise ValueError("Cross-repository PRs require fork_path.")
|
|
309
|
+
if self.fork_path:
|
|
310
|
+
parts = self.fork_path.split("/")
|
|
311
|
+
if len(parts) != 2:
|
|
312
|
+
raise ValueError("fork_path must be owner/repo.")
|
|
313
|
+
RepoArgs(owner=parts[0], repo=parts[1])
|
|
314
|
+
return self
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
class UpdatePullArgs(PullArgs):
|
|
318
|
+
title: Title | None = None
|
|
319
|
+
body: Text | None = None
|
|
320
|
+
state: Literal["open", "closed"] | None = None
|
|
321
|
+
draft: bool | None = None
|
|
322
|
+
labels: Labels | None = None
|
|
323
|
+
milestone_number: PositiveNumber | None = None
|
|
324
|
+
|
|
325
|
+
@model_validator(mode="after")
|
|
326
|
+
def require_change(self) -> UpdatePullArgs:
|
|
327
|
+
if not any(
|
|
328
|
+
getattr(self, field) is not None
|
|
329
|
+
for field in ("title", "body", "state", "draft", "labels", "milestone_number")
|
|
330
|
+
):
|
|
331
|
+
raise ValueError("Provide at least one PR field to update.")
|
|
332
|
+
return self
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
class PullCommentArgs(PullArgs):
|
|
336
|
+
body: Annotated[str, Field(min_length=1, max_length=65_536)]
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
class MergePullArgs(PullArgs):
|
|
340
|
+
merge_method: Literal["merge", "rebase"] = "merge"
|
|
341
|
+
squash: bool = False
|
|
342
|
+
title: Title | None = None
|
|
343
|
+
description: Text | None = None
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
@dataclass(frozen=True)
|
|
347
|
+
class ToolSpec:
|
|
348
|
+
name: str
|
|
349
|
+
description: str
|
|
350
|
+
arguments: type[RepoArgs]
|
|
351
|
+
read_only: bool = True
|
|
352
|
+
destructive: bool = False
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
SPECS = (
|
|
356
|
+
ToolSpec("get_repository", "Read a GitCode repository's metadata and permissions.", RepoArgs),
|
|
357
|
+
ToolSpec(
|
|
358
|
+
"get_clone_info",
|
|
359
|
+
"Get credential-free Git URLs and execution-environment guidance; does not clone files.",
|
|
360
|
+
RepoArgs,
|
|
361
|
+
),
|
|
362
|
+
ToolSpec("list_branches", "Read one page of GitCode repository branches.", PageArgs),
|
|
363
|
+
ToolSpec("get_branch", "Read a GitCode branch and its current commit.", BranchArgs),
|
|
364
|
+
ToolSpec(
|
|
365
|
+
"get_file_contents",
|
|
366
|
+
"Read a repository file at a chosen ref; preserves the API content encoding.",
|
|
367
|
+
FileArgs,
|
|
368
|
+
),
|
|
369
|
+
ToolSpec(
|
|
370
|
+
"get_repository_tree",
|
|
371
|
+
"Read one upstream page of a Git tree, optionally recursive or under file_path. Follow next_page to inspect the remaining entries.",
|
|
372
|
+
TreeArgs,
|
|
373
|
+
),
|
|
374
|
+
ToolSpec(
|
|
375
|
+
"list_commits",
|
|
376
|
+
"Read one page of repository commits, optionally filtered by ref or path.",
|
|
377
|
+
CommitsArgs,
|
|
378
|
+
),
|
|
379
|
+
ToolSpec("get_commit", "Read one repository commit and its API-provided details.", CommitArgs),
|
|
380
|
+
ToolSpec(
|
|
381
|
+
"create_branch",
|
|
382
|
+
"Create a new GitCode branch from an existing reference.",
|
|
383
|
+
CreateBranchArgs,
|
|
384
|
+
False,
|
|
385
|
+
),
|
|
386
|
+
ToolSpec(
|
|
387
|
+
"create_file",
|
|
388
|
+
"Create a file and publish one commit on an explicit existing GitCode branch. Accepts UTF-8 or Base64, up to 256 KiB decoded. Use update_file for existing files. No automatic retries or multi-file atomicity.",
|
|
389
|
+
CreateFileArgs,
|
|
390
|
+
False,
|
|
391
|
+
),
|
|
392
|
+
ToolSpec(
|
|
393
|
+
"update_file",
|
|
394
|
+
"Replace a file and publish one commit. First read it at the target branch and supply its Blob SHA. Up to 256 KiB decoded; no force, automatic retry, or branch-head CAS guarantee.",
|
|
395
|
+
UpdateFileArgs,
|
|
396
|
+
False,
|
|
397
|
+
True,
|
|
398
|
+
),
|
|
399
|
+
ToolSpec(
|
|
400
|
+
"delete_file",
|
|
401
|
+
"Delete a file and publish one commit on an explicit branch. Requires the file's current Blob SHA from that branch. No force, automatic retry, or multi-file rollback.",
|
|
402
|
+
DeleteFileArgs,
|
|
403
|
+
False,
|
|
404
|
+
True,
|
|
405
|
+
),
|
|
406
|
+
ToolSpec(
|
|
407
|
+
"list_issues",
|
|
408
|
+
"Read one page of GitCode issues, with state, labels, or text filters.",
|
|
409
|
+
ListIssuesArgs,
|
|
410
|
+
),
|
|
411
|
+
ToolSpec("get_issue", "Read a GitCode issue by its repository issue number.", IssueArgs),
|
|
412
|
+
ToolSpec("list_issue_comments", "Read one page of comments on a GitCode issue.", IssuePageArgs),
|
|
413
|
+
ToolSpec(
|
|
414
|
+
"create_issue",
|
|
415
|
+
"Create a GitCode issue with title, body, and optional labels or assignee.",
|
|
416
|
+
CreateIssueArgs,
|
|
417
|
+
False,
|
|
418
|
+
),
|
|
419
|
+
ToolSpec(
|
|
420
|
+
"update_issue",
|
|
421
|
+
"Update an issue; title is required and state actions are close or reopen.",
|
|
422
|
+
UpdateIssueArgs,
|
|
423
|
+
False,
|
|
424
|
+
True,
|
|
425
|
+
),
|
|
426
|
+
ToolSpec(
|
|
427
|
+
"add_issue_comment", "Post a new comment on a GitCode issue.", IssueCommentArgs, False
|
|
428
|
+
),
|
|
429
|
+
ToolSpec(
|
|
430
|
+
"list_labels",
|
|
431
|
+
"Read a client-side page of labels after one size-bounded unpaged upstream fetch. Each page re-fetches the collection.",
|
|
432
|
+
PageArgs,
|
|
433
|
+
),
|
|
434
|
+
ToolSpec(
|
|
435
|
+
"list_milestones",
|
|
436
|
+
"Read a client-side page of milestones after one size-bounded unpaged upstream fetch. Each page re-fetches the collection.",
|
|
437
|
+
PageArgs,
|
|
438
|
+
),
|
|
439
|
+
ToolSpec(
|
|
440
|
+
"list_pull_requests",
|
|
441
|
+
"Read one page of GitCode pull requests; reviewer semantics follow GitCode.",
|
|
442
|
+
ListPullsArgs,
|
|
443
|
+
),
|
|
444
|
+
ToolSpec(
|
|
445
|
+
"get_pull_request",
|
|
446
|
+
"Read a GitCode pull request and its current merge/review state.",
|
|
447
|
+
PullArgs,
|
|
448
|
+
),
|
|
449
|
+
ToolSpec(
|
|
450
|
+
"list_pull_request_files",
|
|
451
|
+
"Read a client-side page of changed PR files after one size-bounded unpaged upstream fetch. Pages are not a stable snapshot; oversized responses require local git diff.",
|
|
452
|
+
PullPageArgs,
|
|
453
|
+
),
|
|
454
|
+
ToolSpec(
|
|
455
|
+
"get_pull_request_diff",
|
|
456
|
+
"Read GitCode's structured PR diff from files.json with a hard response-size limit. Preserves native diff_refs and content; use local git diff for oversized or omitted content.",
|
|
457
|
+
PullArgs,
|
|
458
|
+
),
|
|
459
|
+
ToolSpec(
|
|
460
|
+
"list_pull_request_comments",
|
|
461
|
+
"Read one page of GitCode pull-request comments.",
|
|
462
|
+
PullPageArgs,
|
|
463
|
+
),
|
|
464
|
+
ToolSpec(
|
|
465
|
+
"list_pull_request_commits",
|
|
466
|
+
"Read one page of commits in a GitCode pull request.",
|
|
467
|
+
PullPageArgs,
|
|
468
|
+
),
|
|
469
|
+
ToolSpec(
|
|
470
|
+
"create_pull_request",
|
|
471
|
+
"Create a PR; use fork_path for forks. GitCode assignees are reviewers. Verify source changes already exist remotely, through file tools or Git push.",
|
|
472
|
+
CreatePullArgs,
|
|
473
|
+
False,
|
|
474
|
+
),
|
|
475
|
+
ToolSpec(
|
|
476
|
+
"update_pull_request",
|
|
477
|
+
"Update supported PR fields without changing the base branch or forcing a merge.",
|
|
478
|
+
UpdatePullArgs,
|
|
479
|
+
False,
|
|
480
|
+
True,
|
|
481
|
+
),
|
|
482
|
+
ToolSpec(
|
|
483
|
+
"add_pull_request_comment",
|
|
484
|
+
"Post a general PR comment; does not create a GitHub request-changes review.",
|
|
485
|
+
PullCommentArgs,
|
|
486
|
+
False,
|
|
487
|
+
),
|
|
488
|
+
ToolSpec(
|
|
489
|
+
"approve_pull_request",
|
|
490
|
+
"Submit GitCode's native review/approval with force=false. Post review text separately using add_pull_request_comment; request-changes is not emulated.",
|
|
491
|
+
PullArgs,
|
|
492
|
+
False,
|
|
493
|
+
),
|
|
494
|
+
ToolSpec(
|
|
495
|
+
"merge_pull_request",
|
|
496
|
+
"Merge a PR using GitCode checks; never force-merges. Squash is a separate boolean, not a merge method.",
|
|
497
|
+
MergePullArgs,
|
|
498
|
+
False,
|
|
499
|
+
True,
|
|
500
|
+
),
|
|
501
|
+
)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
class GitCodeTools:
|
|
505
|
+
"""Synchronous catalog; the server runs calls in a bounded worker thread."""
|
|
506
|
+
|
|
507
|
+
def __init__(
|
|
508
|
+
self,
|
|
509
|
+
api: GitCodeAPI,
|
|
510
|
+
*,
|
|
511
|
+
allowed_repositories: Iterable[str] = (),
|
|
512
|
+
read_only: bool = False,
|
|
513
|
+
) -> None:
|
|
514
|
+
self.api = api
|
|
515
|
+
self.read_only = read_only
|
|
516
|
+
self.allowed_repositories = frozenset(allowed_repositories)
|
|
517
|
+
for repository in self.allowed_repositories:
|
|
518
|
+
parts = repository.split("/")
|
|
519
|
+
try:
|
|
520
|
+
if len(parts) != 2:
|
|
521
|
+
raise ValueError
|
|
522
|
+
RepoArgs(owner=parts[0], repo=parts[1])
|
|
523
|
+
except (ValueError, ValidationError):
|
|
524
|
+
raise GitCodeError(
|
|
525
|
+
"invalid_configuration", "Repository allowlist entries must be owner/repo."
|
|
526
|
+
) from None
|
|
527
|
+
self._specs = {f"gitcode_{spec.name}": spec for spec in SPECS}
|
|
528
|
+
|
|
529
|
+
def list_tools(self) -> list[Tool]:
|
|
530
|
+
return [
|
|
531
|
+
Tool(
|
|
532
|
+
name=name,
|
|
533
|
+
description=spec.description,
|
|
534
|
+
inputSchema=spec.arguments.model_json_schema(),
|
|
535
|
+
outputSchema={"type": "object", "additionalProperties": True},
|
|
536
|
+
annotations=ToolAnnotations(
|
|
537
|
+
readOnlyHint=spec.read_only,
|
|
538
|
+
destructiveHint=spec.destructive,
|
|
539
|
+
idempotentHint=spec.read_only,
|
|
540
|
+
openWorldHint=True,
|
|
541
|
+
),
|
|
542
|
+
)
|
|
543
|
+
for name, spec in self._specs.items()
|
|
544
|
+
if not self.read_only or spec.read_only
|
|
545
|
+
]
|
|
546
|
+
|
|
547
|
+
def _authorize_repository(self, owner: str, repo: str) -> None:
|
|
548
|
+
if self.allowed_repositories and f"{owner}/{repo}" not in self.allowed_repositories:
|
|
549
|
+
raise GitCodeError(
|
|
550
|
+
"repository_not_allowed", "This repository is outside the configured allowlist."
|
|
551
|
+
)
|
|
552
|
+
|
|
553
|
+
def call(self, name: str, arguments: dict[str, Any] | None) -> dict[str, Any]:
|
|
554
|
+
spec = self._specs.get(name)
|
|
555
|
+
if spec is None:
|
|
556
|
+
raise GitCodeError("unknown_tool", "The requested GitCode tool does not exist.")
|
|
557
|
+
if self.read_only and not spec.read_only:
|
|
558
|
+
raise GitCodeError(
|
|
559
|
+
"read_only", "Write tools are disabled by the server's read-only policy."
|
|
560
|
+
)
|
|
561
|
+
try:
|
|
562
|
+
model = spec.arguments.model_validate(arguments if arguments is not None else {})
|
|
563
|
+
except ValidationError:
|
|
564
|
+
raise GitCodeError(
|
|
565
|
+
"invalid_arguments", "Tool arguments do not match the tool's JSON schema."
|
|
566
|
+
) from None
|
|
567
|
+
data = model.model_dump(exclude_none=True)
|
|
568
|
+
owner, repo = data.pop("owner"), data.pop("repo")
|
|
569
|
+
self._authorize_repository(owner, repo)
|
|
570
|
+
if spec.name == "create_pull_request" and data.get("fork_path"):
|
|
571
|
+
source_owner, source_repo = data["fork_path"].split("/")
|
|
572
|
+
self._authorize_repository(source_owner, source_repo)
|
|
573
|
+
result = self._execute(spec.name, owner, repo, data)
|
|
574
|
+
if not isinstance(result, dict) or "data" not in result:
|
|
575
|
+
result = {"data": result}
|
|
576
|
+
return {"repository": f"{owner}/{repo}", **result}
|
|
577
|
+
|
|
578
|
+
def _execute(self, action: str, owner: str, repo: str, data: dict[str, Any]) -> Any:
|
|
579
|
+
# owner/repo are schema-validated literal path names; all other path
|
|
580
|
+
# values are encoded as segments and never interpolated as API URLs.
|
|
581
|
+
prefix = f"/repos/{segment(owner)}/{segment(repo)}"
|
|
582
|
+
for field in ("labels", "assignees", "testers"):
|
|
583
|
+
if isinstance(data.get(field), list):
|
|
584
|
+
data[field] = ",".join(data[field])
|
|
585
|
+
if action in {"get_repository", "get_clone_info"}:
|
|
586
|
+
repository = self.api.repos.get(owner, repo)
|
|
587
|
+
if action == "get_repository":
|
|
588
|
+
return {"data": repository}
|
|
589
|
+
if not isinstance(repository, dict):
|
|
590
|
+
raise GitCodeError(
|
|
591
|
+
"invalid_response", "GitCode did not return repository metadata."
|
|
592
|
+
)
|
|
593
|
+
return {
|
|
594
|
+
"data": {
|
|
595
|
+
"https_url": f"https://gitcode.com/{owner}/{repo}.git",
|
|
596
|
+
"ssh_url": f"git@gitcode.com:{owner}/{repo}.git",
|
|
597
|
+
"default_branch": repository.get("default_branch"),
|
|
598
|
+
"cloned": False,
|
|
599
|
+
"execution_note": "Run git clone in the same execution environment that will edit and test the code. A remote MCP server's filesystem is not the dot workspace.",
|
|
600
|
+
"authentication_note": "Use a local credential helper or SSH agent; never embed a token in a clone URL.",
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
if action == "list_branches":
|
|
604
|
+
return self.api.page(f"{prefix}/branches", **data)
|
|
605
|
+
if action == "get_branch":
|
|
606
|
+
return self.api.get(f"{prefix}/branches/{segment(data['branch'])}")
|
|
607
|
+
if action == "get_file_contents":
|
|
608
|
+
return self.api.files.get(owner, repo, data.pop("path"), **data)
|
|
609
|
+
if action == "get_repository_tree":
|
|
610
|
+
sha = data.pop("sha")
|
|
611
|
+
data["recursive"] = 1 if data["recursive"] else 0
|
|
612
|
+
tree = self.api.get(f"{prefix}/git/trees/{segment(sha)}", params=data)
|
|
613
|
+
if not isinstance(tree, dict):
|
|
614
|
+
raise GitCodeError(
|
|
615
|
+
"invalid_response", "GitCode did not return the expected tree object."
|
|
616
|
+
)
|
|
617
|
+
result = self.api.page_result(
|
|
618
|
+
tree.get("tree"), page=data["page"], per_page=data["per_page"]
|
|
619
|
+
)
|
|
620
|
+
result["upstream_metadata"] = {
|
|
621
|
+
key: value for key, value in tree.items() if key != "tree"
|
|
622
|
+
}
|
|
623
|
+
result["upstream_truncated"] = tree.get("truncated")
|
|
624
|
+
return result
|
|
625
|
+
if action == "list_commits":
|
|
626
|
+
return self.api.page(f"{prefix}/commits", **data)
|
|
627
|
+
if action == "get_commit":
|
|
628
|
+
return self.api.get(f"{prefix}/commits/{segment(data['sha'])}")
|
|
629
|
+
if action == "create_branch":
|
|
630
|
+
return self.api.post(f"{prefix}/branches", json=data)
|
|
631
|
+
if action in FILE_WRITE_METHODS:
|
|
632
|
+
return write_file(self.api, owner, repo, action, data)
|
|
633
|
+
if action == "list_issues":
|
|
634
|
+
items = self.api.issues.list(owner, repo, **data)
|
|
635
|
+
return self.api.page_result(items, page=data["page"], per_page=data["per_page"])
|
|
636
|
+
if action == "get_issue":
|
|
637
|
+
return self.api.issues.get(owner, repo, str(data["issue_number"]))
|
|
638
|
+
if action == "list_issue_comments":
|
|
639
|
+
number = data.pop("issue_number")
|
|
640
|
+
return self.api.page(f"{prefix}/issues/{number}/comments", **data)
|
|
641
|
+
if action == "create_issue":
|
|
642
|
+
return self.api.issues.create(owner, repo, **data)
|
|
643
|
+
if action == "update_issue":
|
|
644
|
+
number = data.pop("issue_number")
|
|
645
|
+
return self.api.issues.update(owner, repo, str(number), **data)
|
|
646
|
+
if action == "add_issue_comment":
|
|
647
|
+
return self.api.issues.comment(owner, repo, str(data["issue_number"]), data["body"])
|
|
648
|
+
if action == "list_labels":
|
|
649
|
+
items = self.api.issues.list_labels(owner, repo)
|
|
650
|
+
return self.api.collection_page_result(items, **data)
|
|
651
|
+
if action == "list_milestones":
|
|
652
|
+
items = self.api.issues.list_milestones(owner, repo)
|
|
653
|
+
return self.api.collection_page_result(items, **data)
|
|
654
|
+
if action == "list_pull_requests":
|
|
655
|
+
items = self.api.pulls.list(owner, repo, **data)
|
|
656
|
+
return self.api.page_result(items, page=data["page"], per_page=data["per_page"])
|
|
657
|
+
if action == "get_pull_request":
|
|
658
|
+
return self.api.pulls.get(owner, repo, data["pull_number"])
|
|
659
|
+
if action == "list_pull_request_files":
|
|
660
|
+
number = data.pop("pull_number")
|
|
661
|
+
items = self.api.get(f"{prefix}/pulls/{number}/files")
|
|
662
|
+
return self.api.collection_page_result(items, **data)
|
|
663
|
+
if action in {"list_pull_request_comments", "list_pull_request_commits"}:
|
|
664
|
+
number = data.pop("pull_number")
|
|
665
|
+
resource = action.rsplit("_", 1)[1]
|
|
666
|
+
# The upstream comments service eagerly fetches all pages.
|
|
667
|
+
# Keep MCP calls bounded by using its client for one page.
|
|
668
|
+
return self.api.page(f"{prefix}/pulls/{number}/{resource}", **data)
|
|
669
|
+
if action == "get_pull_request_diff":
|
|
670
|
+
diff = self.api.get(f"{prefix}/pulls/{data['pull_number']}/files.json")
|
|
671
|
+
if not isinstance(diff, dict) or not isinstance(diff.get("diffs"), list):
|
|
672
|
+
raise GitCodeError(
|
|
673
|
+
"invalid_response", "GitCode did not return the expected structured diff."
|
|
674
|
+
)
|
|
675
|
+
return {"data": diff, "format": "gitcode_structured_diff"}
|
|
676
|
+
if action == "create_pull_request":
|
|
677
|
+
data["inner_issue_nums"] = ";".join(str(number) for number in data.pop("issue_numbers"))
|
|
678
|
+
return self.api.pulls.create(owner, repo, **data)
|
|
679
|
+
if action == "update_pull_request":
|
|
680
|
+
number = data.pop("pull_number")
|
|
681
|
+
return self.api.pulls.update(owner, repo, number, **data)
|
|
682
|
+
if action == "add_pull_request_comment":
|
|
683
|
+
return self.api.pulls.comment(owner, repo, data["pull_number"], data["body"])
|
|
684
|
+
if action == "approve_pull_request":
|
|
685
|
+
return self.api.pulls.review(owner, repo, data["pull_number"], force=False)
|
|
686
|
+
if action == "merge_pull_request":
|
|
687
|
+
number = data.pop("pull_number")
|
|
688
|
+
return self.api.pulls.merge(owner, repo, number, **data)
|
|
689
|
+
raise GitCodeError("unknown_tool", "The requested GitCode tool does not exist.")
|