Skip to main content
Glama

clone_repository

Clone a GitLab repository to a local directory using the project ID. Optionally specify SSH or a personal access token for authentication.

Instructions

Clone a GitLab repository to local path.

Args:
    project_id: GitLab project ID
    local_path: Local directory path (optional, defaults to project name)
    use_ssh: Use SSH URL instead of HTTPS (default: False)
    token: GitLab Personal Access Token (optional)
    ctx: MCP context (automatically injected)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
project_idYes
local_pathNo
use_sshNo
tokenNo
ctxNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The 'clone_repository' tool handler: fetches project info from GitLab API, constructs clone URL (SSH or HTTPS with token embedding), runs 'git clone' via subprocess, and returns the result.
    @mcp.tool()
    async def clone_repository(project_id: int, local_path: str = None, use_ssh: bool = False, token: str = None, ctx=None) -> str:
        """Clone a GitLab repository to local path.
        
        Args:
            project_id: GitLab project ID
            local_path: Local directory path (optional, defaults to project name)
            use_ssh: Use SSH URL instead of HTTPS (default: False)
            token: GitLab Personal Access Token (optional)
            ctx: MCP context (automatically injected)
        """
        import subprocess
        import os as os_module
        
        # Get project info
        project_data = await make_gitlab_request(f"/projects/{project_id}", ctx=ctx, token=token)
        
        if isinstance(project_data, dict) and "error" in project_data:
            return f"Error getting project info: {project_data['error']}"
        
        # Get clone URL
        clone_url = project_data['ssh_url_to_repo'] if use_ssh else project_data['http_url_to_repo']
        
        # If HTTPS and token available, add token to URL
        if not use_ssh:
            # Use the provided token or fall back to environment variable
            clone_token = token or os_module.getenv("GITLAB_TOKEN")
            if clone_token:
                # Replace https:// with https://gitlab-ci-token:TOKEN@
                clone_url = clone_url.replace("https://", f"https://gitlab-ci-token:{clone_token}@")
        
        # Set local path
        if not local_path:
            local_path = f"./{project_data['name']}"
        
        try:
            # Execute git clone
            result = subprocess.run(
                ["git", "clone", clone_url, local_path],
                capture_output=True,
                text=True,
                timeout=300  # 5 minute timeout
            )
            
            if result.returncode == 0:
                return f"Repository cloned successfully to: {local_path}\nProject: {project_data['name']} ({project_data['path_with_namespace']})"
            else:
                return f"Error cloning repository: {result.stderr}"
                
        except subprocess.TimeoutExpired:
            return "Error: Clone operation timed out (5 minutes)"
        except FileNotFoundError:
            return "Error: Git command not found. Please install Git."
        except Exception as e:
            return f"Error cloning repository: {str(e)}"
  • The '@mcp.tool()' decorator registers 'clone_repository' as an MCP tool on the FastMCP instance.
    # Clone Operations
    @mcp.tool()
    async def clone_repository(project_id: int, local_path: str = None, use_ssh: bool = False, token: str = None, ctx=None) -> str:
  • The docstring and function signature define the input schema: project_id (int), local_path (optional str), use_ssh (bool default False), token (optional str), and ctx (auto-injected context).
    async def clone_repository(project_id: int, local_path: str = None, use_ssh: bool = False, token: str = None, ctx=None) -> str:
        """Clone a GitLab repository to local path.
        
        Args:
            project_id: GitLab project ID
            local_path: Local directory path (optional, defaults to project name)
            use_ssh: Use SSH URL instead of HTTPS (default: False)
            token: GitLab Personal Access Token (optional)
            ctx: MCP context (automatically injected)
        """
  • The 'make_gitlab_request' helper function is used by 'clone_repository' to fetch project info from the GitLab API.
    async def make_gitlab_request(endpoint: str, method: str = "GET", data: dict = None, ctx=None, token: str = None) -> dict[str, Any] | None:
        """Make a request to GitLab API with proper error handling."""
        # Priority: 1. Explicit token parameter, 2. Context headers, 3. Environment variable
        
        # If no explicit token provided, try to get from context
        if not token and ctx and hasattr(ctx, 'request_context') and ctx.request_context:
            # Try to get from request headers
            if hasattr(ctx.request_context, 'headers'):
                token = ctx.request_context.headers.get('GITLAB_TOKEN')
        
        # Fallback to environment variable
        if not token:
            token = os.getenv("GITLAB_TOKEN")
        
        if not token:
            return {"error": "GitLab token not provided. Please provide a token parameter, GITLAB_TOKEN in the request headers, or set the environment variable."}
        
        # Get GitLab URL (from context or environment)
        gitlab_url = os.getenv("GITLAB_URL", "https://gitlab.com")
        
        headers = {
            "PRIVATE-TOKEN": token,
            "Content-Type": "application/json"
        }
        
        url = f"{gitlab_url}/api/v4{endpoint}"
        
        async with httpx.AsyncClient() as client:
            try:
                if method == "GET":
                    response = await client.get(url, headers=headers, timeout=30.0)
                elif method == "POST":
                    response = await client.post(url, headers=headers, json=data, timeout=30.0)
                elif method == "PUT":
                    response = await client.put(url, headers=headers, json=data, timeout=30.0)
                elif method == "DELETE":
                    response = await client.delete(url, headers=headers, timeout=30.0)
                
                response.raise_for_status()
                return response.json() if response.content else {"success": True}
            except Exception as e:
                return {"error": str(e)}
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so description must disclose behavioral traits. It mentions optional parameters but lacks details on side effects (e.g., overwriting existing directories), authentication requirements, or default behavior (HTTPS vs SSH). This is a mutating tool with insufficient transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Very concise: a single-line purpose followed by a clean Args list. No fluff, every sentence adds value. Front-loaded with the action.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Even with an output schema, the description omits important context such as authentication requirements, error conditions (e.g., directory already exists), and success/ failure indicators. For a mutation tool with no annotations, this is insufficient.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so description compensates well. Each parameter is explained with type, optionality, and defaults (e.g., local_path defaults to project name, use_ssh defaults to False). Adds meaningful context beyond the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clearly states the action 'Clone a GitLab repository to local path' with a specific verb and resource. Differentiates from sibling 'clone_group_repositories' by focusing on a single repository.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool vs alternatives like clone_group_repositories. No mention of prerequisites (e.g., Git installation, network access) or context (e.g., private repos needing tokens).

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/skmprb/gitlab-clone-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server