Skip to main content
Glama
AstroMined

PyGithub MCP Server

by AstroMined

get_file_contents

Retrieve file contents from any GitHub repository by specifying owner, repository name, file path, and optional branch. Access code, documentation, or configuration files stored in GitHub repositories.

Instructions

Get contents of a file in a GitHub repository.

Args:
    params: Dictionary with file parameters
        - owner: Repository owner (username or organization)
        - repo: Repository name
        - path: Path to file/directory
        - branch: Branch to get contents from (optional)

Returns:
    MCP response with file content data

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paramsYes

Implementation Reference

  • MCP tool handler for get_file_contents: validates params, calls operations function, formats response as MCP content
    @tool()
    def get_file_contents(params: Dict) -> Dict:
        """Get contents of a file in a GitHub repository.
    
        Args:
            params: Dictionary with file parameters
                - owner: Repository owner (username or organization)
                - repo: Repository name
                - path: Path to file/directory
                - branch: Branch to get contents from (optional)
    
        Returns:
            MCP response with file content data
        """
        try:
            logger.debug(f"get_file_contents called with params: {params}")
            # Convert dict to Pydantic model
            content_params = GetFileContentsParams(**params)
            
            # Call operation
            result = repositories.get_file_contents(content_params)
            
            logger.debug(f"Got result for path: {content_params.path}")
            return {
                "content": [{"type": "text", "text": json.dumps(result, indent=2)}]
            }
        except ValidationError as e:
            logger.error(f"Validation error: {e}")
            return {
                "content": [{"type": "error", "text": f"Validation error: {str(e)}"}],
                "is_error": True
            }
        except GitHubError as e:
            logger.error(f"GitHub error: {e}")
            return {
                "content": [{"type": "error", "text": format_github_error(e)}],
                "is_error": True
            }
        except Exception as e:
            logger.error(f"Unexpected error: {e}")
            logger.error(traceback.format_exc())
            error_msg = str(e) if str(e) else "An unexpected error occurred"
            return {
                "content": [{"type": "error", "text": f"Internal server error: {error_msg}"}],
                "is_error": True
            }
  • Core logic for fetching file contents from GitHub API, handles files and directories
    def get_file_contents(params: GetFileContentsParams) -> Dict[str, Any]:
        """Get contents of a file in a repository.
    
        Args:
            params: Parameters for getting file contents
    
        Returns:
            File content data in our schema
    
        Raises:
            GitHubError: If file access fails
        """
        logger.debug(f"Getting file contents: {params.owner}/{params.repo}/{params.path}")
        try:
            client = GitHubClient.get_instance()
            repository = client.get_repo(f"{params.owner}/{params.repo}")
            
            # Build kwargs from Pydantic model
            kwargs = {"path": params.path}
            if params.branch:
                kwargs["ref"] = params.branch
            
            # Get file contents
            content_file = repository.get_contents(**kwargs)
            
            # Handle case where get_contents returns a list (for directories)
            if isinstance(content_file, list):
                return {
                    "is_directory": True,
                    "path": params.path,
                    "contents": [convert_file_content(item) for item in content_file]
                }
            
            # Handle case where get_contents returns a single file
            return convert_file_content(content_file)
        except GithubException as e:
            logger.error(f"GitHub exception when getting file contents: {str(e)}")
            raise client._handle_github_exception(e, resource_hint="content_file")
  • Pydantic schema for GetFileContentsParams defining input validation
    class GetFileContentsParams(RepositoryRef):
        """Parameters for getting file contents."""
    
        model_config = ConfigDict(strict=True)
        
        path: str = Field(..., description="Path to file/directory")
        branch: Optional[str] = Field(None, description="Branch to get contents from")
    
        @field_validator('path')
        @classmethod
        def validate_path(cls, v):
            """Validate that path is not empty."""
            if not v.strip():
                raise ValueError("path cannot be empty")
            return v
  • Registration of repository tools including get_file_contents with the MCP server
    def register(mcp: FastMCP) -> None:
        """Register all repository tools with the MCP server.
    
        Args:
            mcp: The MCP server instance
        """
        from pygithub_mcp_server.tools import register_tools
        from .tools import (
            get_repository,
            create_repository,
            fork_repository,
            search_repositories,
            get_file_contents,
            create_or_update_file,
            push_files,
            create_branch,
            list_commits
        )
    
        # Register all repository tools
        register_tools(mcp, [
            get_repository,
            create_repository,
            fork_repository,
            search_repositories,
            get_file_contents,
            create_or_update_file,
            push_files,
            create_branch,
            list_commits
        ])
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It states the action 'Get contents' but lacks details on behavioral traits such as authentication requirements, rate limits, error handling, or whether it's read-only (implied but not confirmed). This leaves significant gaps for a tool interacting with an external API like GitHub.

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?

The description is well-structured and appropriately sized, with a clear opening sentence followed by organized 'Args' and 'Returns' sections. Every sentence adds value without redundancy, making it efficient and easy to parse.

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

Completeness3/5

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

Given the complexity of a GitHub API tool with no annotations and no output schema, the description is partially complete. It covers the purpose and parameters well but lacks details on behavioral aspects, return format specifics, and usage context, leaving room for improvement in guiding an AI agent fully.

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?

The description adds substantial meaning beyond the input schema, which has 0% coverage and only indicates a generic 'params' object. It explicitly lists and describes four parameters (owner, repo, path, branch), including their purposes and optionality, effectively compensating for the poor schema documentation.

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

Purpose4/5

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

The description clearly states the verb 'Get' and the resource 'contents of a file in a GitHub repository', making the purpose specific and understandable. However, it does not explicitly differentiate from sibling tools like 'get_repository' or 'get_issue', which might retrieve different types of data from GitHub, so it misses full sibling differentiation.

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?

The description provides no guidance on when to use this tool versus alternatives. For example, it does not mention when to choose this over 'get_repository' for file content or 'list_commits' for commit details, nor does it specify prerequisites or exclusions for usage.

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/AstroMined/pygithub-mcp-server'

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