-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
2463 lines (2115 loc) · 75.9 KB
/
Copy pathserver.py
File metadata and controls
2463 lines (2115 loc) · 75.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
codeberg-mcp — MCP server for Codeberg (Gitea API v1)
crafted by effece 🧉
Multi-account support via CODEBERG_ACCOUNTS env var:
{"personal": "tok_abc...", "work": "tok_xyz..."}
Default account: CODEBERG_DEFAULT_ACCOUNT (defaults to the first configured account)
Transports:
HTTP/SSE → for claude.ai custom connectors (default: uvicorn server.py)
stdio → for Claude Code (MCP_TRANSPORT=stdio python server.py)
Tools:
Repos → list_repos, get_repo, create_repo
Files → get_file, create_file, update_file, delete_file, list_dir
PRs → list_pulls, get_pull, create_pull, merge_pull
Branches → list_branches, create_branch
Commits → get_latest_commit, compare_refs
Actions → list_workflow_runs, get_workflow_run, get_workflow_logs
Issues → list_issues, get_issue, create_issue, comment_on_issue
Account → list_user_keys, list_user_emails
Settings → set_repo_actions_enabled, list_repo_secrets
"""
import base64
import functools
import json
import os
from contextlib import asynccontextmanager
from pathlib import Path
from dotenv import load_dotenv
load_dotenv(Path(__file__).parent / ".env", override=True)
import httpx # noqa: E402
from mcp.server.fastmcp import FastMCP # noqa: E402
# ── server ──────────────────────────────────────────────────────────────────
# Defaults to Codeberg; override for any Gitea/Forgejo instance via env.
BASE_URL = os.environ.get("CODEBERG_BASE_URL", "https://codeberg.org/api/v1")
# Shared httpx client — created once via lifespan, reuses connections
_client: httpx.AsyncClient | None = None
_accounts: dict[str, str] = {}
_default_account: str = ""
import logging # noqa: E402
logger = logging.getLogger("codeberg-mcp")
async def _validate_accounts() -> None:
"""Hit GET /user for each configured account; log result. Never raises."""
for name, token in _accounts.items():
try:
r = await _client.get("/user", headers={"Authorization": f"token {token}"})
if r.is_success:
login = r.json().get("login", "?")
logger.info(f"account {name}: live ({login})")
else:
logger.warning(
f"account {name}: FAILED ({r.status_code} — token invalid?)"
)
except Exception as e:
logger.warning(f"account {name}: FAILED (exception: {e})")
@asynccontextmanager
async def _lifespan(server):
global _client, _accounts, _default_account
raw = os.environ.get("CODEBERG_ACCOUNTS", "").strip()
if not raw:
raise RuntimeError(
"CODEBERG_ACCOUNTS is not set. "
'Expected JSON: {"personal": "tok_...", "work": "tok_..."}'
)
_accounts = json.loads(raw)
if not _accounts:
raise RuntimeError("CODEBERG_ACCOUNTS is empty.")
# Default to CODEBERG_DEFAULT_ACCOUNT, else the first configured account.
_default_account = os.environ.get("CODEBERG_DEFAULT_ACCOUNT") or next(
iter(_accounts)
)
if _default_account not in _accounts:
raise RuntimeError(
f"Default account '{_default_account}' not found in CODEBERG_ACCOUNTS. "
f"Available: {', '.join(_accounts.keys())}"
)
_client = httpx.AsyncClient(
base_url=BASE_URL,
headers={
"Content-Type": "application/json",
"Accept": "application/json",
},
timeout=20,
)
await _validate_accounts()
try:
yield
finally:
await _client.aclose()
_client = None
mcp = FastMCP(
"codeberg",
instructions=(
"Interact with Codeberg repositories, files, pull requests, and branches "
"via the Gitea REST API. Supports multiple accounts — use the 'account' "
"parameter to switch. The default is the first account in CODEBERG_ACCOUNTS "
"(or set CODEBERG_DEFAULT_ACCOUNT). All write operations "
"(create/update/delete) require a "
"commit message. update_file and delete_file require the current file "
"sha — call get_file first. merge_pull supports merge, rebase, and squash. "
"ERROR CONTRACT: on any Codeberg API failure a tool returns "
'{"error": "Codeberg API <status>: <detail>", "status": <int>} '
"instead of its normal result (including tools that normally return a "
"list). Treat any result containing top-level 'error' and 'status' "
"keys as a failure and read 'error' for the reason."
),
lifespan=_lifespan,
)
def _get_client(account: str | None = None) -> tuple[httpx.AsyncClient, dict]:
"""Return the shared client and auth headers for the given account."""
if _client is None:
raise RuntimeError("Codeberg client not initialized — server not started?")
name = account or _default_account
token = _accounts.get(name)
if not token:
raise RuntimeError(
f"Unknown account '{name}'. Available: {', '.join(_accounts.keys())}"
)
return _client, {"Authorization": f"token {token}"}
class CodebergAPIError(RuntimeError):
"""A non-2xx response from the Codeberg API.
Subclasses RuntimeError so existing `pytest.raises(RuntimeError, ...)`
unit tests on `_raise` keep passing, while carrying the structured
`.status` / `.detail` the `catch_api_errors` decorator returns to the
caller.
"""
def __init__(self, status: int, detail: str) -> None:
self.status = status
self.detail = detail
super().__init__(f"Codeberg API {status}: {detail}")
# Forgejo's POST /issues 500s above ~4k-char bodies (observed empirically
# across sessions; see memory reference_codeberg_create_issue_workaround).
# Soft limit — we still attempt, but annotate the result / error with the
# smoke-create + PATCH workaround so the caller isn't left guessing.
_ISSUE_BODY_SOFT_LIMIT = 3500
def _detail(response: httpx.Response) -> str:
"""Extract a human-readable detail string from a non-2xx response.
JSON 'message' or 'error' field if present, else a truncated body.
"""
try:
body = response.json()
return body.get("message") or body.get("error") or str(body)[:300]
except Exception:
return response.text[:300]
def _raise(response: httpx.Response) -> None:
"""Raise CodebergAPIError on non-2xx responses.
The decorator turns this into a structured error result so the message
reaches Claude instead of being eaten by FastMCP's wrapper.
"""
if response.is_success:
return
raise CodebergAPIError(response.status_code, _detail(response))
def _safe_list(value: object) -> list:
"""Return `value` if it's a list, else `[]`.
Forgejo returns `null` (not `[]`) for empty `labels` / `assignees` /
similar collection fields. `dict.get(key, [])` does NOT guard this —
the key exists with a null value, so the default is never used and
`for x in None` raises `'NoneType' object is not iterable`.
"""
return value if isinstance(value, list) else []
def catch_api_errors(fn):
"""Convert CodebergAPIError into a structured tool result.
Applied UNDER `@mcp.tool()` so FastMCP introspects the original
signature (functools.wraps preserves it). API errors become
`{"error": str(e), "status": e.status}` — the message reaches the
caller instead of being swallowed. Non-API
exceptions (programming bugs) propagate unchanged.
"""
@functools.wraps(fn)
async def wrapper(*args, **kwargs):
try:
return await fn(*args, **kwargs)
except CodebergAPIError as e:
return {"error": str(e), "status": e.status}
return wrapper
async def _paginate(
fetch_page,
limit: int,
page: int,
all: bool,
cap_pages: int = 10,
) -> list[dict]:
"""Either fetch one page, or sweep pages 1..cap_pages until empty.
fetch_page(page) is a callable that fetches a single page and returns a
list. Returns the flat list across all fetched pages.
"""
if not all:
return await fetch_page(page)
out: list[dict] = []
hit_cap = True
for p in range(1, cap_pages + 1):
batch = await fetch_page(p)
if not batch:
hit_cap = False
break
out.extend(batch)
if hit_cap:
logger.warning(
f"all=True stopped at {cap_pages * limit} items (page {cap_pages}). "
"Increase cap or use explicit pagination."
)
return out
# ── repo tools ───────────────────────────────────────────────────────────────
@mcp.tool()
@catch_api_errors
async def list_repos(
username: str | None = None,
limit: int = 20,
page: int = 1,
all: bool = False,
account: str | None = None,
) -> list[dict]:
"""
List repositories.
If `username` is omitted, lists repos for the authenticated user.
If `username` is provided, lists that user's public repos.
Args:
username: Codeberg username to query (optional).
limit: Max repos to return per page (default 20, max 50).
page: Page number for single-page fetch (default 1).
all: If true, auto-paginate until empty (cap 10 pages = 500 items).
account: Codeberg account to use (default: the configured default account).
Returns:
List of repo objects with keys: full_name, description, private,
html_url, stars_count, forks_count, default_branch, updated.
"""
client, auth = _get_client(account)
url = f"/users/{username}/repos" if username else "/user/repos"
async def fetch_page(p: int) -> list[dict]:
r = await client.get(
url, headers=auth, params={"limit": min(limit, 50), "page": p}
)
_raise(r)
return [
{
"full_name": repo["full_name"],
"description": repo.get("description", ""),
"private": repo["private"],
"html_url": repo["html_url"],
"stars_count": repo.get("stars_count", 0),
"forks_count": repo.get("forks_count", 0),
"default_branch": repo.get("default_branch", "main"),
"updated": repo.get("updated", ""),
}
for repo in r.json()
]
return await _paginate(fetch_page, min(limit, 50), page, all)
@mcp.tool()
@catch_api_errors
async def get_repo(
owner: str,
repo: str,
account: str | None = None,
) -> dict:
"""
Get details for a single repository.
Args:
owner: Repository owner (username or org).
repo: Repository name.
account: Codeberg account to use (default: the configured default account).
Returns:
Repo object with full metadata.
"""
client, auth = _get_client(account)
r = await client.get(f"/repos/{owner}/{repo}", headers=auth)
_raise(r)
data = r.json()
return {
"full_name": data["full_name"],
"description": data.get("description", ""),
"private": data["private"],
"html_url": data["html_url"],
"clone_url": data.get("clone_url", ""),
"ssh_url": data.get("ssh_url", ""),
"default_branch": data.get("default_branch", "main"),
"stars_count": data.get("stars_count", 0),
"forks_count": data.get("forks_count", 0),
"open_issues_count": data.get("open_issues_count", 0),
"language": data.get("language", ""),
"topics": data.get("topics", []),
"updated": data.get("updated", ""),
}
@mcp.tool()
@catch_api_errors
async def create_repo(
name: str,
description: str = "",
private: bool = False,
auto_init: bool = True,
default_branch: str = "main",
gitignores: str = "",
license_template: str = "",
account: str | None = None,
) -> dict:
"""
Create a new repository under the authenticated user's account.
Args:
name: Repository name (no spaces, use hyphens).
description: Short description (optional).
private: Whether to make the repo private (default False).
auto_init: Initialize with a README (default True).
default_branch: Default branch name (default 'main').
gitignores: Comma-separated gitignore templates, e.g. 'Python,Node'.
license_template: SPDX license identifier, e.g. 'MIT', 'GPL-3.0'.
account: Codeberg account to use (default: the configured default account).
Returns:
Created repo object with full_name, html_url, clone_url, ssh_url.
"""
payload = {
"name": name,
"description": description,
"private": private,
"auto_init": auto_init,
"default_branch": default_branch,
}
if gitignores:
payload["gitignores"] = gitignores
if license_template:
payload["license"] = license_template
client, auth = _get_client(account)
r = await client.post("/user/repos", headers=auth, json=payload)
_raise(r)
data = r.json()
return {
"full_name": data["full_name"],
"html_url": data["html_url"],
"clone_url": data.get("clone_url", ""),
"ssh_url": data.get("ssh_url", ""),
"private": data["private"],
"default_branch": data.get("default_branch", "main"),
}
# ── file tools ───────────────────────────────────────────────────────────────
@mcp.tool()
@catch_api_errors
async def get_file(
owner: str,
repo: str,
path: str,
ref: str | None = None,
account: str | None = None,
) -> dict:
"""
Read a file's contents from a repository.
Args:
owner: Repository owner.
repo: Repository name.
path: File path within the repo, e.g. 'src/main.py'.
ref: Branch, tag, or commit SHA (defaults to repo's default branch).
account: Codeberg account to use (default: the configured default account).
Returns:
Dict with 'path', 'content' (decoded text), 'sha', 'size', 'html_url'.
"""
params = {}
if ref:
params["ref"] = ref
client, auth = _get_client(account)
r = await client.get(
f"/repos/{owner}/{repo}/contents/{path}", headers=auth, params=params
)
_raise(r)
data = r.json()
if data.get("type") == "dir":
raise ValueError(
f"'{path}' is a directory. Use list_dir to browse directories."
)
raw = data.get("content", "")
# Gitea returns base64 content with potential newlines
decoded = base64.b64decode(raw.replace("\n", "")).decode("utf-8", errors="replace")
return {
"path": data["path"],
"content": decoded,
"sha": data["sha"],
"size": data.get("size", 0),
"encoding": "utf-8",
"html_url": data.get("html_url", ""),
}
@mcp.tool()
@catch_api_errors
async def create_file(
owner: str,
repo: str,
path: str,
content: str,
message: str,
branch: str | None = None,
author_name: str | None = None,
author_email: str | None = None,
account: str | None = None,
) -> dict:
"""
Create a new file in a repository.
Args:
owner: Repository owner.
repo: Repository name.
path: File path within the repo, e.g. 'docs/notes.md'.
content: Plain text content to write (will be base64-encoded).
message: Commit message.
branch: Target branch (defaults to repo's default branch).
author_name: Commit author name (defaults to token owner's name).
author_email: Commit author email (defaults to token owner's email).
account: Codeberg account to use (default: the configured default account).
Returns:
Dict with 'path', 'sha', 'html_url', 'commit_sha'.
"""
encoded = base64.b64encode(content.encode("utf-8")).decode("ascii")
payload: dict = {"message": message, "content": encoded}
if branch:
payload["branch"] = branch
if author_name and author_email:
payload["author"] = {"name": author_name, "email": author_email}
client, auth = _get_client(account)
r = await client.post(
f"/repos/{owner}/{repo}/contents/{path}", headers=auth, json=payload
)
_raise(r)
data = r.json()
return {
"path": data["content"]["path"],
"sha": data["content"]["sha"],
"html_url": data["content"].get("html_url", ""),
"commit_sha": data["commit"]["sha"],
"commit_message": data["commit"]["message"],
}
@mcp.tool()
@catch_api_errors
async def update_file(
owner: str,
repo: str,
path: str,
content: str,
message: str,
sha: str,
branch: str | None = None,
author_name: str | None = None,
author_email: str | None = None,
account: str | None = None,
) -> dict:
"""
Update an existing file in a repository.
The `sha` of the current file is required to prevent conflicts.
Use get_file first to retrieve the current sha.
Args:
owner: Repository owner.
repo: Repository name.
path: File path within the repo.
content: New plain text content (will be base64-encoded).
message: Commit message.
sha: Current file SHA (from get_file).
branch: Target branch (defaults to repo's default branch).
author_name: Commit author name (optional).
author_email: Commit author email (optional).
account: Codeberg account to use (default: the configured default account).
Returns:
Dict with 'path', 'sha', 'html_url', 'commit_sha'.
"""
encoded = base64.b64encode(content.encode("utf-8")).decode("ascii")
payload: dict = {"message": message, "content": encoded, "sha": sha}
if branch:
payload["branch"] = branch
if author_name and author_email:
payload["author"] = {"name": author_name, "email": author_email}
client, auth = _get_client(account)
r = await client.put(
f"/repos/{owner}/{repo}/contents/{path}", headers=auth, json=payload
)
_raise(r)
data = r.json()
return {
"path": data["content"]["path"],
"sha": data["content"]["sha"],
"html_url": data["content"].get("html_url", ""),
"commit_sha": data["commit"]["sha"],
"commit_message": data["commit"]["message"],
}
@mcp.tool()
@catch_api_errors
async def delete_file(
owner: str,
repo: str,
path: str,
message: str,
sha: str,
branch: str | None = None,
account: str | None = None,
) -> dict:
"""
Delete a file from a repository.
The `sha` of the current file is required.
Use get_file first to retrieve the current sha.
Args:
owner: Repository owner.
repo: Repository name.
path: File path within the repo.
message: Commit message.
sha: Current file SHA (from get_file).
branch: Target branch (defaults to repo's default branch).
account: Codeberg account to use (default: the configured default account).
Returns:
Dict with 'commit_sha' and 'commit_message'.
"""
payload: dict = {"message": message, "sha": sha}
if branch:
payload["branch"] = branch
client, auth = _get_client(account)
r = await client.request(
"DELETE",
f"/repos/{owner}/{repo}/contents/{path}",
headers=auth,
json=payload,
)
_raise(r)
data = r.json()
return {
"commit_sha": data["commit"]["sha"],
"commit_message": data["commit"]["message"],
}
@mcp.tool()
@catch_api_errors
async def list_dir(
owner: str,
repo: str,
path: str = "",
ref: str | None = None,
account: str | None = None,
) -> list[dict]:
"""
List the contents of a directory in a repository.
Args:
owner: Repository owner.
repo: Repository name.
path: Directory path (empty string = repo root).
ref: Branch, tag, or commit SHA (defaults to default branch).
account: Codeberg account to use (default: the configured default account).
Returns:
List of entries with 'name', 'path', 'type' ('file'|'dir'), 'sha', 'size'.
"""
params = {}
if ref:
params["ref"] = ref
client, auth = _get_client(account)
r = await client.get(
f"/repos/{owner}/{repo}/contents/{path}", headers=auth, params=params
)
_raise(r)
data = r.json()
if isinstance(data, dict):
raise ValueError(f"'{path}' is a file, not a directory. Use get_file instead.")
return [
{
"name": entry["name"],
"path": entry["path"],
"type": entry["type"],
"sha": entry["sha"],
"size": entry.get("size", 0),
}
for entry in data
]
# ── pull request tools ──────────────────────────────────────────────────────
@mcp.tool()
@catch_api_errors
async def list_pulls(
owner: str,
repo: str,
state: str = "open",
limit: int = 20,
page: int = 1,
all: bool = False,
account: str | None = None,
) -> list[dict]:
"""
List pull requests for a repository.
Args:
owner: Repository owner.
repo: Repository name.
state: Filter by state: 'open', 'closed', or 'all' (default 'open').
limit: Max results per page (default 20, max 50).
page: Page number for single-page fetch (default 1).
all: If true, auto-paginate until empty (cap 10 pages = 500 items).
account: Codeberg account to use (default: the configured default account).
Returns:
List of PR objects with keys: number, title, state, head_branch,
base_branch, user, html_url, created, updated, merged.
"""
client, auth = _get_client(account)
async def fetch_page(p: int) -> list[dict]:
r = await client.get(
f"/repos/{owner}/{repo}/pulls",
headers=auth,
params={"state": state, "limit": min(limit, 50), "page": p},
)
_raise(r)
return [
{
"number": pr["number"],
"title": pr["title"],
"state": pr["state"],
"head_branch": pr["head"]["label"],
"base_branch": pr["base"]["label"],
"user": pr["user"]["login"],
"html_url": pr["html_url"],
"created": pr.get("created_at", ""),
"updated": pr.get("updated_at", ""),
"merged": pr.get("merged", False),
}
for pr in r.json()
]
return await _paginate(fetch_page, min(limit, 50), page, all)
@mcp.tool()
@catch_api_errors
async def get_pull(
owner: str,
repo: str,
index: int,
account: str | None = None,
) -> dict:
"""
Get details for a single pull request.
Args:
owner: Repository owner.
repo: Repository name.
index: PR number.
account: Codeberg account to use (default: the configured default account).
Returns:
PR object with full metadata including mergeable status.
"""
client, auth = _get_client(account)
r = await client.get(f"/repos/{owner}/{repo}/pulls/{index}", headers=auth)
_raise(r)
pr = r.json()
return {
"number": pr["number"],
"title": pr["title"],
"body": pr.get("body", ""),
"state": pr["state"],
"head_branch": pr["head"]["label"],
"base_branch": pr["base"]["label"],
"user": pr["user"]["login"],
"html_url": pr["html_url"],
"mergeable": pr.get("mergeable", None),
"merged": pr.get("merged", False),
"merged_by": pr.get("merged_by", {}).get("login", "")
if pr.get("merged_by")
else "",
"additions": pr.get("additions", 0),
"deletions": pr.get("deletions", 0),
"changed_files": pr.get("changed_files", 0),
"created": pr.get("created_at", ""),
"updated": pr.get("updated_at", ""),
}
@mcp.tool()
@catch_api_errors
async def create_pull(
owner: str,
repo: str,
title: str,
head: str,
base: str,
body: str = "",
account: str | None = None,
) -> dict:
"""
Create a pull request.
Args:
owner: Repository owner.
repo: Repository name.
title: PR title.
head: Source branch name.
base: Target branch name (e.g. 'main').
body: PR description (optional).
account: Codeberg account to use (default: the configured default account).
Returns:
Created PR object with number, title, html_url.
"""
client, auth = _get_client(account)
r = await client.post(
f"/repos/{owner}/{repo}/pulls",
headers=auth,
json={"title": title, "head": head, "base": base, "body": body},
)
_raise(r)
pr = r.json()
return {
"number": pr["number"],
"title": pr["title"],
"state": pr["state"],
"html_url": pr["html_url"],
"head_branch": pr["head"]["label"],
"base_branch": pr["base"]["label"],
}
@mcp.tool()
@catch_api_errors
async def merge_pull(
owner: str,
repo: str,
index: int,
method: str = "merge",
account: str | None = None,
) -> dict:
"""
Merge a pull request. Branch deletion is never automatic — handle manually.
Args:
owner: Repository owner.
repo: Repository name.
index: PR number.
method: Merge method: 'merge', 'rebase', or 'squash' (default 'merge').
account: Codeberg account to use (default: the configured default account).
Returns:
Dict with merged status and method used.
"""
if method not in ("merge", "rebase", "squash"):
raise ValueError(
f"Invalid merge method '{method}'. Use 'merge', 'rebase', or 'squash'."
)
client, auth = _get_client(account)
r = await client.post(
f"/repos/{owner}/{repo}/pulls/{index}/merge",
headers=auth,
json={"do": method, "delete_branch_after_merge": False},
)
_raise(r)
return {"merged": True, "method": method}
# ── branch tools ────────────────────────────────────────────────────────────
@mcp.tool()
@catch_api_errors
async def list_branches(
owner: str,
repo: str,
limit: int = 20,
page: int = 1,
all: bool = False,
account: str | None = None,
) -> list[dict]:
"""
List branches for a repository.
Args:
owner: Repository owner.
repo: Repository name.
limit: Max results per page (default 20, max 50).
page: Page number for single-page fetch (default 1).
all: If true, auto-paginate until empty (cap 10 pages = 500 items).
account: Codeberg account to use (default: the configured default account).
Returns:
List of branch objects with name, commit SHA, and protected status.
"""
client, auth = _get_client(account)
async def fetch_page(p: int) -> list[dict]:
r = await client.get(
f"/repos/{owner}/{repo}/branches",
headers=auth,
params={"limit": min(limit, 50), "page": p},
)
_raise(r)
return [
{
"name": b["name"],
"commit_sha": b["commit"]["id"],
"commit_message": b["commit"].get("message", "").split("\n")[0],
"protected": b.get("protected", False),
}
for b in r.json()
]
return await _paginate(fetch_page, min(limit, 50), page, all)
@mcp.tool()
@catch_api_errors
async def create_branch(
owner: str,
repo: str,
branch_name: str,
old_branch: str | None = None,
account: str | None = None,
) -> dict:
"""
Create a new branch.
Args:
owner: Repository owner.
repo: Repository name.
branch_name: Name for the new branch.
old_branch: Source branch to create from (defaults to repo's default branch).
account: Codeberg account to use (default: the configured default account).
Returns:
Created branch object with name and commit SHA.
"""
payload: dict = {"new_branch_name": branch_name}
if old_branch:
payload["old_branch_name"] = old_branch
client, auth = _get_client(account)
r = await client.post(
f"/repos/{owner}/{repo}/branches",
headers=auth,
json=payload,
)
_raise(r)
b = r.json()
return {
"name": b["name"],
"commit_sha": b["commit"]["id"],
"protected": b.get("protected", False),
}
# ── commit tools ─────────────────────────────────────────────────────────────
async def _get_default_branch(owner: str, repo: str, account: str | None) -> str:
"""Internal helper: fetch the repo's default branch via /repos/{o}/{r}."""
client, auth = _get_client(account)
r = await client.get(f"/repos/{owner}/{repo}", headers=auth)
_raise(r)
return r.json().get("default_branch", "main")
@mcp.tool()
@catch_api_errors
async def get_latest_commit(
owner: str,
repo: str,
branch: str | None = None,
account: str | None = None,
) -> dict:
"""
Return the latest commit on a branch. If `branch` is None, resolves to
the repo's default branch via a lookup.
Args:
owner: Repository owner (username or org).
repo: Repository name.
branch: Branch name (optional — defaults to repo's default_branch).
account: Codeberg account to use (default: the configured default account).
Returns:
{sha, message, author, committer, timestamp, url}
"""
if branch is None:
branch = await _get_default_branch(owner, repo, account)
client, auth = _get_client(account)
r = await client.get(f"/repos/{owner}/{repo}/branches/{branch}", headers=auth)
_raise(r)
commit = r.json()["commit"]
return {
"sha": commit["id"],
"message": commit["message"],
"author": commit["author"],
"committer": commit["committer"],
"timestamp": commit.get("timestamp", ""),
"url": commit.get("url", ""),
}
@mcp.tool()
@catch_api_errors
async def compare_refs(
owner: str,
repo: str,
base: str,
head: str,
account: str | None = None,
) -> dict:
"""