summaryrefslogtreecommitdiff
path: root/servers/gitlab_python/src/mcp_server_gitlab_python/server.py
blob: 09d362830058708794fe08a8d67d040742d2d5e6 (plain)
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
import logging
import os
from typing import Any

import gitlab
import yaml
from mcp.server.fastmcp import FastMCP

logger = logging.getLogger("mcp_gitlab_python_server")


def get_git_remote_url(working_directory: str) -> str | None:
    try:
        from git import Repo

        repo = Repo(working_directory)
        return repo.remotes.origin.url
    except Exception as e:
        logger.warning(f"Could not get git remote url: {e}")
    return None


def parse_gitlab_url_from_remote(remote_url: str) -> str | None:
    # Handles both SSH and HTTPS remotes
    if remote_url.startswith("git@"):
        # git@gitlab.com:namespace/project.git
        host = remote_url.split("@")[1].split(":")[0]
        return f"https://{host}"
    elif remote_url.startswith("https://"):
        # https://gitlab.com/namespace/project.git
        parts = remote_url.split("/")
        if len(parts) > 2:
            return f"{parts[0]}//{parts[2]}"
    return None


def get_token_from_glab_config(host: str) -> str | None:
    """
    Retrieve the GitLab token for a specific host from the glab-cli config file.
    """
    config_path = os.path.expanduser("~/.config/glab-cli/config.yml")
    if not os.path.exists(config_path):
        return None
    try:
        with open(config_path) as f:
            config = yaml.safe_load(f)
        hosts = config.get("hosts", {})
        # Try direct match
        if host in hosts and "token" in hosts[host]:
            return hosts[host]["token"]
        # Try matching by api_host if present
        for _h, data in hosts.items():  # Renamed h to _h for Ruff B007
            if data.get("api_host") == host and "token" in data:
                return data["token"]
    except Exception as e:
        logger.warning(f"Could not parse glab-cli config: {e}")
    return None


def get_gitlab_settings(working_directory: str) -> tuple[str, str]:
    """
    Determine the GitLab URL and token to use, matching the token to the detected host.

    Args:
        working_directory (str): The working directory to detect the git remote.

    Returns:
        tuple[str, str]: (url, token)
    """
    # URL
    url = os.environ.get("GITLAB_HOST")
    if not url:
        remote_url = get_git_remote_url(working_directory)
        if remote_url:
            url = parse_gitlab_url_from_remote(remote_url)
    if not url:
        url = "https://gitlab.com"  # fallback default
    # Ensure scheme is present
    if not url.startswith("http://") and not url.startswith("https://"):
        url = f"https://{url}"
    # Extract host from URL
    from urllib.parse import urlparse

    parsed = urlparse(url)
    host = (
        parsed.hostname
        or url.replace("https://", "").replace("http://", "").split("/")[0]
    )
    # Token
    token = os.environ.get("GITLAB_TOKEN")
    if not token:
        token = get_token_from_glab_config(host)
    if not token:
        logger.error(
            f"No GitLab token found for host '{host}' in env or glab-cli config."
        )
        raise RuntimeError(
            f"No GitLab token found for host '{host}' in env or glab-cli config."
        )
    return url, token


class GitLabPythonServer:
    def __init__(self, working_directory: str) -> None:
        url, token = get_gitlab_settings(working_directory)
        self.gl = gitlab.Gitlab(url, private_token=token)
        self.gl.auth()

    def find_project(self, project_name: str) -> list[dict[str, Any]]:
        projects = self.gl.projects.list(search=project_name, all=True)
        return [
            {
                "id": p.id,
                "name": p.name,
                "path_with_namespace": p.path_with_namespace,
                "web_url": p.web_url,
                "description": p.description,
            }
            for p in projects
        ]

    def search_issues(self, project: str, **filters: object) -> dict[str, Any]:
        try:
            proj = self.gl.projects.get(project)
            issues = proj.issues.list(**filters, all=True)
            return {
                "issues": [
                    {
                        "id": i.id,
                        "iid": i.iid,
                        "title": i.title,
                        "web_url": i.web_url,
                        "state": i.state,
                        "created_at": i.created_at,
                        "updated_at": i.updated_at,
                    }
                    for i in issues
                ]
            }
        except Exception as e:
            return {"error": str(e)}

    def create_issue(
        self,
        project: str,
        title: str,
        description: str,
        epic_id: int | None = None,
        **kwargs: object,
    ) -> dict[str, Any]:
        """Create a new GitLab issue.

        Args:
            project (str): The project full path or ID.
            title (str): The title of the issue.
            description (str): The description of the issue.
            epic_id (int | None): The global ID of the epic to attach the issue to.
            **kwargs: Additional fields for the issue.

        Returns:
            dict[str, Any]: Dictionary with the issue URL or error message.
        """
        try:
            proj = self.gl.projects.get(project)
            issue = proj.issues.create(
                {
                    "title": title,
                    "description": description,
                    **kwargs,
                }
            )

            # If epic_id is provided, attach the issue to the epic
            if epic_id is not None:
                try:
                    # Find the epic by searching through groups
                    # This is a simplified approach - in practice, you might want to
                    # require the group to be specified or search more efficiently
                    groups = self.gl.groups.list(all=True)
                    epic_found = False

                    for group in groups:
                        try:
                            epic = group.epics.get(epic_id)
                            epic.issues.create({"issue_id": issue.id})
                            epic_found = True
                            logger.info(
                                f"Successfully attached issue {issue.id} to epic "
                                f"{epic_id}"
                            )
                            break
                        except Exception as e:
                            logger.debug(f"Failed to get epic {epic_id} from group: {e}")
                            continue

                    if not epic_found:
                        logger.warning(
                            f"Could not find epic {epic_id} to attach issue {issue.id}"
                        )
                except Exception as e:
                    logger.error(
                        f"Failed to attach issue {issue.id} to epic {epic_id}: {e}"
                    )
                    # Don't fail the entire operation if epic attachment fails

            return {"url": issue.web_url}
        except Exception as e:
            return {"error": str(e)}

    def update_issue(
        self,
        project: str,
        issue_iid: int,
        epic_id: int | None = None,
        **kwargs: object,
    ) -> dict[str, Any]:
        """Update an existing GitLab issue.

        Args:
            project (str): The project full path or ID.
            issue_iid (int): The internal ID of the issue.
            epic_id (int | None): The global ID of the epic to attach the issue to.
            **kwargs: Fields to update (e.g., title, description, labels, etc.).

        Returns:
            dict[str, Any]: Dictionary with the issue URL or error message.
        """
        try:
            proj = self.gl.projects.get(project)
            issue = proj.issues.get(issue_iid)
            for k, v in kwargs.items():
                setattr(issue, k, v)
            issue.save()

            # If epic_id is provided, attach the issue to the epic
            if epic_id is not None:
                try:
                    # Find the epic by searching through groups
                    groups = self.gl.groups.list(all=True)
                    epic_found = False

                    for group in groups:
                        try:
                            epic = group.epics.get(epic_id)
                            epic.issues.create({"issue_id": issue.id})
                            epic_found = True
                            logger.info(
                                f"Successfully attached issue {issue.id} to epic "
                                f"{epic_id}"
                            )
                            break
                        except Exception as e:
                            logger.debug(f"Failed to get epic {epic_id} from group: {e}")
                            continue

                    if not epic_found:
                        logger.warning(
                            f"Could not find epic {epic_id} to attach issue {issue.id}"
                        )
                except Exception as e:
                    logger.error(
                        f"Failed to attach issue {issue.id} to epic {epic_id}: {e}"
                    )
                    # Don't fail the entire operation if epic attachment fails

            return {"url": issue.web_url}
        except Exception as e:
            logger.error(f"Failed to update issue {project}#{issue_iid}: {e}")
            return {"error": str(e)}

    def get_mr_diff(
        self,
        project: str,
        mr_iid: int,
        max_size_kb: int = 100,
        filter_extensions: list[str] | None = None,
    ) -> dict[str, Any]:
        import tempfile

        if filter_extensions is None:
            filter_extensions = [".lock", ".log"]
        try:
            proj = self.gl.projects.get(project)
            mr = proj.mergerequests.get(mr_iid)
            diffs = mr.diffs.list()
            logger.debug(
                f"Fetched {len(diffs)} file diffs for MR {mr_iid} in project {project}"
            )
            diff_content = ""
            for i, diff in enumerate(diffs):
                logger.debug(f"Processing diff #{i}: {diff}")
                old_path = diff.old_path or "/dev/null"
                new_path = diff.new_path or "/dev/null"
                diff_text = diff.diff
                if diff_text is None:
                    logger.warning(
                        f"Skipping diff #{i} due to missing diff text: {diff}"
                    )
                    continue
                if any(
                    old_path.endswith(ext) or new_path.endswith(ext)
                    for ext in filter_extensions
                ):
                    logger.debug(
                        f"Skipping diff #{i} due to filter extension: "
                        f"{old_path}, {new_path}"
                    )
                    continue
                diff_content += f"diff --git a/{old_path} b/{new_path}\n"
                diff_content += diff_text + "\n"
            diff_size_kb = len(diff_content.encode("utf-8")) / 1024
            logger.debug(f"Total diff size: {diff_size_kb:.2f} KB")
            if diff_size_kb > max_size_kb:
                try:
                    with tempfile.NamedTemporaryFile(
                        mode="w",
                        suffix=".diff",
                        prefix="mr_diff_",
                        delete=False,
                        encoding="utf-8",
                    ) as temp_file:
                        temp_file.write(diff_content)
                        temp_path = temp_file.name
                    logger.info(f"Diff too large, saved to {temp_path}")
                    return {
                        "diff_too_large": True,
                        "size_kb": round(diff_size_kb, 2),
                        "max_size_kb": max_size_kb,
                        "temp_file_path": temp_path,
                        "message": (
                            f"Diff is too large ({diff_size_kb:.2f} KB > "
                            f"{max_size_kb} KB). Content saved to temporary file: "
                            f"{temp_path}"
                        ),
                    }
                except Exception as e:
                    logger.error(f"Failed to create temp file for large diff: {e}")
                    return {
                        "error": (
                            f"Diff is too large ({diff_size_kb:.2f} KB) and failed to "
                            f"create temporary file: {str(e)}"
                        )
                    }
            return {
                "diff": diff_content,
                "size_kb": round(diff_size_kb, 2),
                "temp_file_path": None,
            }
        except Exception as e:
            logger.error(f"Exception in get_mr_diff: {e}", exc_info=True)
            return {"error": str(e)}

    def run_ci_pipeline(
        self,
        project: str,
        branch: str = None,
        variables: dict | None = None,
        web_mode: bool = False,
        working_directory: str = None,
    ) -> dict[str, Any]:
        try:
            proj = self.gl.projects.get(project)
            ref = branch
            if not ref:
                # Try to detect current branch using GitPython
                try:
                    from git import Repo

                    repo = Repo(working_directory)
                    ref = repo.active_branch.name
                except Exception:
                    ref = None
            if not ref:
                # If still no branch, let GitLab use default
                ref = proj.default_branch
            # Prepare variables
            pipeline_vars = variables.copy() if variables else {}
            if web_mode:
                pipeline_vars["CI_PIPELINE_SOURCE"] = "web"
            pipeline = proj.pipelines.create(
                {
                    "ref": ref,
                    "variables": [
                        {"key": k, "value": v} for k, v in pipeline_vars.items()
                    ]
                    if pipeline_vars
                    else None,
                }
            )
            info = {
                "success": True,
                "pipeline_id": pipeline.id,
                "pipeline_url": pipeline.web_url,
                "branch": ref,
                "web_mode": web_mode,
            }
            return info
        except Exception as e:
            return {"error": str(e)}

    def find_group(self, group_name: str) -> list[dict[str, Any]]:
        """Find GitLab groups by name or path."""
        groups = self.gl.groups.list(search=group_name, all=True)
        return [
            {
                "id": g.id,
                "name": g.name,
                "full_path": g.full_path,
                "web_url": g.web_url,
                "description": g.description,
            }
            for g in groups
        ]

    def search_epics(self, group: str, **filters: object) -> dict[str, Any]:
        """Search for GitLab epics in a group with various filters.

        Args:
            group (str): The group full path or ID.
            **filters: Additional filters for the search.

        Returns:
            dict[str, Any]: Dictionary with a list of epics or error message.
        """
        try:
            grp = self.gl.groups.get(group)
            epics = grp.epics.list(**filters, all=True)
            return {
                "epics": [
                    {
                        "id": e.id,
                        "iid": e.iid,
                        "title": e.title,
                        "web_url": e.web_url,
                        "state": e.state,
                        "created_at": e.created_at,
                        "updated_at": e.updated_at,
                        "author": getattr(e, "author", None),
                        "labels": getattr(e, "labels", []),
                        "description": getattr(e, "description", None),
                    }
                    for e in epics
                ]
            }
        except Exception as e:
            return {"error": str(e)}

    def create_epic(
        self,
        group: str,
        title: str,
        description: str = "",
        **kwargs: object,
    ) -> dict[str, Any]:
        """Create a new GitLab epic in a group.

        Args:
            group (str): The group full path or ID.
            title (str): The title of the epic.
            description (str): The description of the epic.
            **kwargs: Additional fields for the epic.

        Returns:
            dict[str, Any]: Dictionary with the epic URL or error message.
        """
        try:
            grp = self.gl.groups.get(group)
            data = {"title": title, "description": description}
            data.update(kwargs)
            epic = grp.epics.create(data)
            return {"url": epic.web_url}
        except Exception as e:
            return {"error": str(e)}

    def update_epic(
        self,
        group: str,
        epic_iid: int,
        **kwargs: object,
    ) -> dict[str, Any]:
        """Update an existing GitLab epic.

        Args:
            group (str): The group full path or ID.
            epic_iid (int): The internal ID of the epic.
            **kwargs: Fields to update (e.g., title, description, labels, etc.).

        Returns:
            dict[str, Any]: Dictionary with the epic URL or error message.
        """
        try:
            grp = self.gl.groups.get(group)
            epic = grp.epics.get(epic_iid)
            for k, v in kwargs.items():
                setattr(epic, k, v)
            epic.save()
            return {"url": epic.web_url}
        except Exception as e:
            logger.error(f"Failed to update epic {group}#{epic_iid}: {e}")
            return {"error": str(e)}

    def list_issue_comments(self, project: str, issue_iid: int) -> dict[str, Any]:
        """List all comments (notes) for a given issue.

        Args:
            project (str): The project full path or ID.
            issue_iid (int): The internal ID of the issue.

        Returns:
            dict[str, Any]: Dictionary with a list of comments or error message.
        """
        try:
            proj = self.gl.projects.get(project)
            issue = proj.issues.get(issue_iid)
            notes = issue.notes.list(all=True)
            return {
                "comments": [
                    {
                        "id": n.id,
                        "body": n.body,
                        "author": getattr(n, "author", None),
                        "created_at": n.created_at,
                        "updated_at": n.updated_at,
                        "system": getattr(n, "system", False),
                    }
                    for n in notes
                ]
            }
        except Exception as e:
            return {"error": str(e)}

    def create_issue_comment(
        self, project: str, issue_iid: int, body: str
    ) -> dict[str, Any]:
        """Create a comment (note) on a given issue.

        Args:
            project (str): The project full path or ID.
            issue_iid (int): The internal ID of the issue.
            body (str): The comment text.

        Returns:
            dict[str, Any]: Dictionary with the comment info or error message.
        """
        try:
            proj = self.gl.projects.get(project)
            issue = proj.issues.get(issue_iid)
            note = issue.notes.create({"body": body})
            return {
                "id": note.id,
                "body": note.body,
                "author": getattr(note, "author", None),
                "created_at": note.created_at,
                "updated_at": note.updated_at,
                "system": getattr(note, "system", False),
            }
        except Exception as e:
            return {"error": str(e)}

    def list_epic_comments(self, group: str, epic_iid: int) -> dict[str, Any]:
        """List all comments (notes) for a given epic.

        Args:
            group (str): The group full path or ID.
            epic_iid (int): The internal ID of the epic.

        Returns:
            dict[str, Any]: Dictionary with a list of comments or error message.
        """
        try:
            grp = self.gl.groups.get(group)
            epic = grp.epics.get(epic_iid)
            notes = epic.notes.list(all=True)
            return {
                "comments": [
                    {
                        "id": n.id,
                        "body": n.body,
                        "author": getattr(n, "author", None),
                        "created_at": n.created_at,
                        "updated_at": n.updated_at,
                        "system": getattr(n, "system", False),
                    }
                    for n in notes
                ]
            }
        except Exception as e:
            return {"error": str(e)}

    def create_epic_comment(
        self, group: str, epic_iid: int, body: str
    ) -> dict[str, Any]:
        """Create a comment (note) on a given epic.

        Args:
            group (str): The group full path or ID.
            epic_iid (int): The internal ID of the epic.
            body (str): The comment text.

        Returns:
            dict[str, Any]: Dictionary with the comment info or error message.
        """
        try:
            grp = self.gl.groups.get(group)
            epic = grp.epics.get(epic_iid)
            note = epic.notes.create({"body": body})
            return {
                "id": note.id,
                "body": note.body,
                "author": getattr(note, "author", None),
                "created_at": note.created_at,
                "updated_at": note.updated_at,
                "system": getattr(note, "system", False),
            }
        except Exception as e:
            return {"error": str(e)}


def create_server(host: str = "127.0.0.1", port: int = 8080) -> FastMCP:
    mcp = FastMCP("GitLab Python", host=host, port=port)

    @mcp.tool()
    def find_project(project_name: str, working_directory: str) -> list[dict[str, Any]]:
        """Find GitLab projects by name."""
        server = GitLabPythonServer(working_directory)
        return server.find_project(project_name)

    @mcp.tool()
    def search_issues(
        project: str,
        working_directory: str,
        author_id: int | None = None,
        assignee_id: int | None = None,
        state: str | None = None,
        labels: list[str] | None = None,
        milestone: str | None = None,
        **kwargs: object,
    ) -> dict[str, Any]:
        """Search for GitLab issues with various filters."""
        server = GitLabPythonServer(working_directory)
        filters = {
            k: v
            for k, v in locals().items()
            if v is not None and k not in ["project", "working_directory", "kwargs"]
        }
        if labels:
            filters["labels"] = ",".join(labels)
        filters.update(kwargs)
        return server.search_issues(project, **filters)

    @mcp.tool()
    def create_issue(
        project: str,
        title: str,
        description: str,
        working_directory: str,
        labels: list[str] | None = None,
        assignee_ids: list[int] | None = None,
        milestone_id: int | None = None,
        epic_id: int | None = None,
        **kwargs: object,
    ) -> dict[str, Any]:
        """Create a new GitLab issue.

        Args:
            project (str): The project full path or ID.
            title (str): The title of the issue.
            description (str): The description of the issue.
            working_directory (str): The working directory for context.
            labels (list[str] | None): List of labels to apply to the issue.
            assignee_ids (list[int] | None): List of user IDs to assign the issue to.
            milestone_id (int | None): The ID of the milestone to assign the issue to.
            epic_id (int | None): The global ID of the epic to attach the issue to.
            **kwargs: Additional fields for the issue.

        Returns:
            dict[str, Any]: Dictionary with the issue URL or error message.
        """
        server = GitLabPythonServer(working_directory)
        data = {}
        if labels:
            data["labels"] = labels
        if assignee_ids:
            data["assignee_ids"] = assignee_ids
        if milestone_id:
            data["milestone_id"] = milestone_id
        data.update(kwargs)
        return server.create_issue(project, title, description, epic_id=epic_id, **data)

    @mcp.tool()
    def update_issue(
        project: str,
        issue_iid: int,
        working_directory: str,
        title: str | None = None,
        description: str | None = None,
        state_event: str | None = None,
        labels: list[str] | None = None,
        assignee_ids: list[int] | None = None,
        milestone_id: int | None = None,
        epic_id: int | None = None,
        **kwargs: object,
    ) -> dict[str, Any]:
        """Update an existing GitLab issue.

        Args:
            project (str): The project full path or ID.
            issue_iid (int): The internal ID of the issue.
            working_directory (str): The working directory for context.
            title (str | None): The new title for the issue.
            description (str | None): The new description for the issue.
            state_event (str | None): The state event (e.g., 'close', 'reopen').
            labels (list[str] | None): List of labels to apply to the issue.
            assignee_ids (list[int] | None): List of user IDs to assign the issue to.
            milestone_id (int | None): The ID of the milestone to assign the issue to.
            epic_id (int | None): The global ID of the epic to attach the issue to.
            **kwargs: Additional fields to update.

        Returns:
            dict[str, Any]: Dictionary with the issue URL or error message.
        """
        server = GitLabPythonServer(working_directory)
        data = {}
        if title is not None:
            data["title"] = title
        if description is not None:
            data["description"] = description
        if state_event is not None:
            data["state_event"] = state_event
        if labels is not None:
            data["labels"] = labels
        if assignee_ids is not None:
            data["assignee_ids"] = assignee_ids
        if milestone_id is not None:
            data["milestone_id"] = milestone_id
        data.update(kwargs)
        return server.update_issue(project, issue_iid, epic_id=epic_id, **data)

    @mcp.tool()
    def get_mr_diff(
        project: str,
        mr_iid: int,
        working_directory: str,
        max_size_kb: int = 100,
        filter_extensions: list[str] | None = None,
    ) -> dict[str, Any]:
        """Get the diff for a merge request."""
        server = GitLabPythonServer(working_directory)
        return server.get_mr_diff(
            project=project,
            mr_iid=mr_iid,
            max_size_kb=max_size_kb,
            filter_extensions=filter_extensions,
        )

    @mcp.tool()
    def run_ci_pipeline(
        project: str,
        working_directory: str,
        branch: str = None,
        variables: dict | None = None,
        web_mode: bool = False,
    ) -> dict[str, Any]:
        """Run a CI/CD pipeline on GitLab."""
        server = GitLabPythonServer(working_directory)
        return server.run_ci_pipeline(
            project=project,
            branch=branch,
            variables=variables,
            web_mode=web_mode,
            working_directory=working_directory,
        )

    @mcp.tool()
    def find_group(group_name: str, working_directory: str) -> list[dict[str, Any]]:
        """Find GitLab groups by name or path."""
        server = GitLabPythonServer(working_directory)
        return server.find_group(group_name)

    @mcp.tool()
    def search_epics(
        group: str,
        working_directory: str,
        author_id: int | None = None,
        state: str | None = None,
        labels: list[str] | None = None,
        order_by: str | None = None,
        sort: str | None = None,
        search: str | None = None,
        **kwargs: object,
    ) -> dict[str, Any]:
        """Search for GitLab epics in a group with various filters."""
        server = GitLabPythonServer(working_directory)
        filters = {
            k: v
            for k, v in locals().items()
            if v is not None and k not in ["group", "working_directory", "kwargs"]
        }
        if labels:
            filters["labels"] = ",".join(labels)
        filters.update(kwargs)
        return server.search_epics(group, **filters)

    @mcp.tool()
    def create_epic(
        group: str,
        title: str,
        description: str,
        working_directory: str,
        labels: list[str] | None = None,
        parent_id: int | None = None,
        color: str | None = None,
        confidential: bool | None = None,
        start_date_fixed: str | None = None,
        due_date_fixed: str | None = None,
        **kwargs: object,
    ) -> dict[str, Any]:
        """Create a new GitLab epic in a group."""
        server = GitLabPythonServer(working_directory)
        data = {}
        if labels:
            data["labels"] = labels
        if parent_id is not None:
            data["parent_id"] = parent_id
        if color is not None:
            data["color"] = color
        if confidential is not None:
            data["confidential"] = confidential
        if start_date_fixed is not None:
            data["start_date_fixed"] = start_date_fixed
            data["start_date_is_fixed"] = True
        if due_date_fixed is not None:
            data["due_date_fixed"] = due_date_fixed
            data["due_date_is_fixed"] = True
        data.update(kwargs)
        return server.create_epic(group, title, description, **data)

    @mcp.tool()
    def update_epic(
        group: str,
        epic_iid: int,
        working_directory: str,
        title: str | None = None,
        description: str | None = None,
        state_event: str | None = None,
        labels: list[str] | None = None,
        parent_id: int | None = None,
        color: str | None = None,
        confidential: bool | None = None,
        start_date_fixed: str | None = None,
        due_date_fixed: str | None = None,
        **kwargs: object,
    ) -> dict[str, Any]:
        """Update an existing GitLab epic."""
        server = GitLabPythonServer(working_directory)
        data = {}
        if title is not None:
            data["title"] = title
        if description is not None:
            data["description"] = description
        if state_event is not None:
            data["state_event"] = state_event
        if labels is not None:
            data["labels"] = labels
        if parent_id is not None:
            data["parent_id"] = parent_id
        if color is not None:
            data["color"] = color
        if confidential is not None:
            data["confidential"] = confidential
        if start_date_fixed is not None:
            data["start_date_fixed"] = start_date_fixed
            data["start_date_is_fixed"] = True
        if due_date_fixed is not None:
            data["due_date_fixed"] = due_date_fixed
            data["due_date_is_fixed"] = True
        data.update(kwargs)
        return server.update_epic(group, epic_iid, **data)

    @mcp.tool()
    def list_issue_comments(
        project: str,
        issue_iid: int,
        working_directory: str,
    ) -> dict[str, Any]:
        """List all comments (notes) for a given issue.

        Args:
            project (str): The project full path or ID.
            issue_iid (int): The internal ID of the issue.
            working_directory (str): The working directory for context.

        Returns:
            dict[str, Any]: Dictionary with a list of comments or error message.
        """
        server = GitLabPythonServer(working_directory)
        return server.list_issue_comments(project, issue_iid)

    @mcp.tool()
    def create_issue_comment(
        project: str,
        issue_iid: int,
        body: str,
        working_directory: str,
    ) -> dict[str, Any]:
        """Create a comment (note) on a given issue.

        Args:
            project (str): The project full path or ID.
            issue_iid (int): The internal ID of the issue.
            body (str): The comment text.
            working_directory (str): The working directory for context.

        Returns:
            dict[str, Any]: Dictionary with the comment info or error message.
        """
        server = GitLabPythonServer(working_directory)
        return server.create_issue_comment(project, issue_iid, body)

    @mcp.tool()
    def list_epic_comments(
        group: str,
        epic_iid: int,
        working_directory: str,
    ) -> dict[str, Any]:
        """List all comments (notes) for a given epic.

        Args:
            group (str): The group full path or ID.
            epic_iid (int): The internal ID of the epic.
            working_directory (str): The working directory for context.

        Returns:
            dict[str, Any]: Dictionary with a list of comments or error message.
        """
        server = GitLabPythonServer(working_directory)
        return server.list_epic_comments(group, epic_iid)

    @mcp.tool()
    def create_epic_comment(
        group: str,
        epic_iid: int,
        body: str,
        working_directory: str,
    ) -> dict[str, Any]:
        """Create a comment (note) on a given epic.

        Args:
            group (str): The group full path or ID.
            epic_iid (int): The internal ID of the epic.
            body (str): The comment text.
            working_directory (str): The working directory for context.

        Returns:
            dict[str, Any]: Dictionary with the comment info or error message.
        """
        server = GitLabPythonServer(working_directory)
        return server.create_epic_comment(group, epic_iid, body)

    return mcp


async def main(transport_type: str, host: str, port: int) -> None:
    logger.info("Starting MCP GitLab Python Server")
    mcp = create_server(host=host, port=port)
    if transport_type == "stdio":
        logger.info("Server running with stdio transport")
        await mcp.run_stdio_async()
    else:
        logger.info(f"Server running with remote transport on {host}:{port}")
        await mcp.run_sse_async()