get_file_contents
Retrieve file contents from a GitHub repository by specifying owner, repo, path, and optional branch. Ideal for accessing and managing code or document data directly.
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
| Name | Required | Description | Default |
|---|---|---|---|
| params | Yes |
Implementation Reference
- MCP tool handler for get_file_contents: validates params with GetFileContentsParams, calls core operation, handles errors and returns MCP-formatted response.@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 }
- Pydantic input schema GetFileContentsParams defining owner, repo, path, and optional branch with 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
- src/pygithub_mcp_server/tools/repositories/__init__.py:9-39 (registration)Registers the get_file_contents tool (imported from .tools) along with other repository tools using register_tools on 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 ])
- Core business logic for retrieving file or directory contents from GitHub repository using PyGitHub, handles files and directories, converts to internal schema.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")