get_latest_sha
Retrieve the SHA of the most recent commit from a GitHub repository by specifying the owner and repository name.
Instructions
Fetches the SHA of the latest commit in the specified GitHub repository. Args: repo_owner (str): The owner of the GitHub repository. repo_name (str): The name of the GitHub repository. Returns: Optional[str]: The SHA string of the latest commit if found, otherwise None. Error Handling: Logs errors and warnings if the request fails, the response is invalid, or no commits are found. Returns None in case of exceptions or if the repository has no commits.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| repo_owner | Yes | ||
| repo_name | Yes |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
| result | Yes |
Implementation Reference
- The handler method `get_latest_sha` on the `GitHubIntegration` class. Fetches the SHA of the latest commit from a GitHub repository by calling the GitHub commits API endpoint `GET /repos/{owner}/{repo}/commits` and returning the SHA of the first (most recent) commit.
def get_latest_sha(self, repo_owner: str, repo_name: str) -> str | None: """ Fetches the SHA of the latest commit in the specified GitHub repository. Args: repo_owner (str): The owner of the GitHub repository. repo_name (str): The name of the GitHub repository. Returns: Optional[str]: The SHA string of the latest commit if found, otherwise None. Error Handling: Logs errors and warnings if the request fails, the response is invalid, or no commits are found. Returns None in case of exceptions or if the repository has no commits. """ logger.info(f"Fetching latest commit SHA for {repo_owner}/{repo_name}") # Construct the commits URL commits_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/commits" try: # Fetch the latest commit response = httpx.get(commits_url, headers=self._get_headers(), timeout=TIMEOUT) self._raise_for_status(response, f"commits for {repo_owner}/{repo_name}") commits_data = response.json() if commits_data: latest_sha = commits_data[0]["sha"] logger.info(f"Latest commit SHA: {latest_sha}") return latest_sha else: logger.warning("No commits found in the repository") return "No commits found in the repository" except GitHubAuthError: raise except Exception as e: logger.error(f"Error fetching latest commit SHA: {str(e)}") traceback.print_exc() return str(e) - src/mcp_github/issues_pr_analyser.py:137-148 (registration)Registration: `register_tools(self.gi)` introspects all public methods of the `GitHubIntegration` instance (including `get_latest_sha`) and registers each as an MCP tool via `self.mcp.add_tool(method)`.
def _register_tools(self): self.register_tools(self.gi) self.register_tools(self.ip) self.mcp.add_provider(SkillsDirectoryProvider(Path(__file__).parent / "skills")) def register_tools(self, methods: Any = None) -> None: for name in dir(methods): if name.startswith("_"): continue method = getattr(methods, name) if inspect.isroutine(method): self.mcp.add_tool(method) - Helper usage: `create_tag` calls `self.get_latest_sha(repo_owner, repo_name)` to obtain the latest commit SHA before creating a new Git tag referencing that commit.
def create_tag(self, repo_owner: str, repo_name: str, tag_name: str, message: str) -> dict[str, Any]: """ Creates a new tag in the specified GitHub repository. Args: repo_owner (str): The owner of the repository. repo_name (str): The name of the repository. tag_name (str): The name of the tag to create. message (str): The message associated with the tag. Returns: Dict[str, Any]: The response data from the GitHub API if the tag is created successfully. None: If an error occurs during the tag creation process. Error Handling: Logs errors and prints the traceback if fetching the latest commit SHA fails or if the GitHub API request fails. """ logger.info(f"Creating tag {tag_name} in {repo_owner}/{repo_name}") # Construct the tags URL tags_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/git/refs" try: # Fetch the latest commit SHA latest_sha = self.get_latest_sha(repo_owner, repo_name) if not latest_sha: raise ValueError("Failed to fetch the latest commit SHA") # Create the tag response = httpx.post( tags_url, headers=self._get_headers(), json={ "ref": f"refs/tags/{tag_name}", "sha": latest_sha, "message": message, }, timeout=TIMEOUT, ) self._raise_for_status(response, f"create tag {tag_name}") tag_data = response.json() logger.info("Tag created successfully") return tag_data except GitHubAuthError: raise except Exception as e: logger.error(f"Error creating tag: {str(e)}") traceback.print_exc() return {"status": "error", "message": str(e)}