get_file_content
Retrieve the contents of a file in a GitLab repository using project ID, file path, and branch reference.
Instructions
Get content of a repository file.
Args:
project_id: GitLab project ID
file_path: Path to the file
ref: Branch/tag reference (default: main)
token: GitLab Personal Access Token (optional)
ctx: MCP context (automatically injected)Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| project_id | Yes | ||
| file_path | Yes | ||
| ref | No | main | |
| token | No | ||
| ctx | No |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
| result | Yes |
Implementation Reference
- Handler function for the 'get_file_content' tool. Fetches file content from a GitLab repository using the GitLab API's repository files endpoint, URL-encodes the file path, decodes the base64-encoded content, and returns up to 2000 characters of the file content.
@mcp.tool() async def get_file_content(project_id: int, file_path: str, ref: str = "main", token: str = None, ctx=None) -> str: """Get content of a repository file. Args: project_id: GitLab project ID file_path: Path to the file ref: Branch/tag reference (default: main) token: GitLab Personal Access Token (optional) ctx: MCP context (automatically injected) """ import urllib.parse encoded_path = urllib.parse.quote(file_path, safe='') endpoint = f"/projects/{project_id}/repository/files/{encoded_path}?ref={ref}" data = await make_gitlab_request(endpoint, ctx=ctx, token=token) if isinstance(data, dict) and "error" in data: return f"Error: {data['error']}" import base64 try: content = base64.b64decode(data['content']).decode('utf-8') return f"File: {file_path}\n\n{content[:2000]}{'...' if len(content) > 2000 else ''}" except: return "Unable to decode file content" - gitlab_clone_mcp_server/server.py:313-314 (registration)Registration of 'get_file_content' as an MCP tool via the @mcp.tool() decorator on the async function.
@mcp.tool() async def get_file_content(project_id: int, file_path: str, ref: str = "main", token: str = None, ctx=None) -> str: - Input schema/type signature for get_file_content: expects project_id (int), file_path (str), optional ref (str, default 'main'), optional token (str), and automatically injected ctx. Returns a string.
async def get_file_content(project_id: int, file_path: str, ref: str = "main", token: str = None, ctx=None) -> str: """Get content of a repository file. Args: project_id: GitLab project ID file_path: Path to the file ref: Branch/tag reference (default: main) token: GitLab Personal Access Token (optional) ctx: MCP context (automatically injected) """ - Helper function 'make_gitlab_request' used by get_file_content to make authenticated API requests to 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)}