Skip to main content
Glama
saidsef

GitHub PR Issue Analyser

by saidsef

update_pr_branch

Update a pull request branch by merging the base branch into it, ensuring it includes the latest upstream changes.

Instructions

Updates the pull request branch with the latest upstream changes by merging the base branch into the PR branch.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
repo_ownerYesThe owner of the repository.
repo_nameYesThe name of the repository.
pr_numberYesThe pull request number.
expected_head_shaNoOptional SHA of the PR branch head. If provided, GitHub will only update the branch if the current head SHA matches this value.

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main handler for 'update_pr_branch'. This method updates a pull request branch with the latest upstream changes by calling the GitHub API's 'pulls/{pr_number}/update-branch' endpoint via an HTTP PUT request. It accepts repo_owner, repo_name, pr_number, and an optional expected_head_sha parameter.
    def update_pr_branch(
        self,
        repo_owner: str,
        repo_name: str,
        pr_number: int,
        expected_head_sha: str | None = None,
    ) -> dict[str, Any]:
        """
        Updates the pull request branch with the latest upstream changes by merging the base branch into the PR branch.
    
        Args:
            repo_owner: The owner of the repository.
            repo_name: The name of the repository.
            pr_number: The pull request number.
            expected_head_sha: Optional SHA of the PR branch head. If provided, GitHub will only update the
                branch if the current head SHA matches this value.
        Returns:
            dict[str, Any]: The GitHub API response for the branch update request.
        Raises:
            GitHubAuthError: If authentication fails.
            GitHubAPIError: If the request fails.
        """
        logger.info(f"Updating PR branch for {repo_owner}/{repo_name}#{pr_number}")
    
        pr_url = (
            f"https://api.github.com/repos/{repo_owner}/{repo_name}/pulls/{pr_number}/update-branch"
        )
    
        try:
            payload: dict[str, Any] = {}
            if expected_head_sha is not None:
                payload["expected_head_sha"] = expected_head_sha
            response = httpx.put(
                pr_url,
                headers=self._get_headers(),
                json=payload,
                timeout=TIMEOUT,
            )
            self._raise_for_status(response, f"PR #{pr_number} update branch")
            logger.info("PR branch update requested successfully")
            return response.json()
        except GitHubAuthError:
            raise
        except Exception as e:
            logger.error(f"Error updating PR branch: {str(e)}")
            traceback.print_exc()
            return {"status": "error", "message": str(e)}
  • Registration of tools from GitHubIntegration (which includes update_pr_branch). The register_tools method iterates over all public methods of the GitHubIntegration instance using dir() and adds them as MCP tools via self.mcp.add_tool(method). This is how update_pr_branch gets registered as an MCP tool.
    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)
  • The merge_pr method references update_pr_branch in its docstring: 'If merge pr fails use update_pr_branch to update the branch with the latest changes from the base branch and try merging again after CI finishes.' This is the contextual reference that ties the two tools together.
    def merge_pr(
        self,
        repo_owner: str,
        repo_name: str,
        pr_number: int,
        commit_title: str | None = None,
        commit_message: str | None = None,
        merge_method: Literal["merge", "squash", "rebase"] = "squash",
    ) -> dict[str, Any]:
        """
        Merges a specific pull request in a GitHub repository using the specified merge method.
        If merge pr is fails use update_pr_branch to update the branch with the latest changes from the base branch and try merging again after CI finishes.
        Args:
            repo_owner (str): The owner of the repository.
            repo_name (str): The name of the repository.
            pr_number (int): The pull request number to merge.
            commit_title (str, optional): The title for the merge commit. Defaults to None.
            commit_message (str, optional): The message for the merge commit. Defaults to None.
            merge_method (Literal['merge', 'squash', 'rebase'], optional): The merge method to use ('merge', 'squash', or 'rebase'). Defaults to 'squash'.
        Returns:
            Dict[str, Any]: The JSON response from the GitHub API containing merge information if successful.
        Error Handling:
            Logs errors and prints the traceback if the merge fails, returning None.
        """
        logger.info(f"Merging PR {repo_owner}/{repo_name}#{pr_number}")
    
        # Construct the merge URL
        merge_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/pulls/{pr_number}/merge"
    
        try:
            payload: dict[str, Any] = {"merge_method": merge_method}
            if commit_title is not None:
                payload["commit_title"] = commit_title
            if commit_message is not None:
                payload["commit_message"] = commit_message
    
            response = httpx.put(
                merge_url,
                headers=self._get_headers(),
                json=payload,
                timeout=TIMEOUT,
            )
            if not response.is_success:
                self._handle_response_error(
                    response,
                    f"PR #{pr_number} merge in {repo_owner}/{repo_name}",
                )
            merge_data = response.json()
    
            logger.info("PR merged successfully")
            return merge_data
    
        except GitHubAPIError as e:
            if isinstance(e, GitHubAuthError):
                detail = e.message
            else:
                github_msg = (e.response_body or {}).get("message", "") if e.response_body else ""
                detail = github_msg or e.message
            logger.error(f"Error merging PR: {detail}")
            return {"status": "error", "message": detail, "details": e.response_body}
        except httpx.HTTPError as e:
            logger.error(f"Error merging PR: {str(e)}")
            traceback.print_exc()
            return {"status": "error", "message": str(e)}
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 of behavioral disclosure. It states the update is done by merging, but does not mention potential conflicts, failure cases, required permissions, or what happens if the branch is already up-to-date. This leaves significant behavioral gaps.

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?

A single sentence of 20 words that immediately states the purpose and action. No wasted words or repetition. The description is front-loaded with the key verb and resource.

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?

The tool has an output schema (not shown but presence indicated), so return values need not be explained. However, the description is minimal; it does not cover behavior when already up-to-date, conflict handling, or authorization requirements. For a tool with 4 parameters, more completeness is expected.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents each parameter. The description adds operational context but does not enhance understanding of individual parameters beyond what the schema provides. Baseline score of 3 is appropriate.

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

Purpose5/5

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

The description clearly states the verb 'Updates' and the resource 'pull request branch', and specifies the action 'by merging the base branch into the PR branch'. This distinguishes it from sibling tools like 'merge_pr' which merge the PR into the base.

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 does not provide any guidance on when to use this tool versus alternatives such as 'merge_pr' or when not to use it. It lacks context about prerequisites or scenarios where this tool is appropriate.

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/saidsef/mcp-github-pr-issue-analyser'

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