Skip to main content
Glama
AstroMined
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 ])

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