Skip to main content
Glama
AstroMined

PyGithub MCP Server

by AstroMined

create_branch

Create a new branch in a GitHub repository by specifying owner, repository name, branch name, and optional source branch.

Instructions

Create a new branch in a GitHub repository.

Args:
    params: Dictionary with branch parameters
        - owner: Repository owner (username or organization)
        - repo: Repository name
        - branch: Name for new branch
        - from_branch: Source branch (optional, defaults to repo default)

Returns:
    MCP response with branch creation result

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paramsYes

Implementation Reference

  • The MCP tool handler function decorated with @tool(). Validates input parameters using CreateBranchParams, delegates to the operations layer for execution, handles errors, and returns an MCP-formatted response.
    @tool()
    def create_branch(params: Dict) -> Dict:
        """Create a new branch in a GitHub repository.
    
        Args:
            params: Dictionary with branch parameters
                - owner: Repository owner (username or organization)
                - repo: Repository name
                - branch: Name for new branch
                - from_branch: Source branch (optional, defaults to repo default)
    
        Returns:
            MCP response with branch creation result
        """
        try:
            logger.debug(f"create_branch called with params: {params}")
            # Convert dict to Pydantic model
            branch_params = CreateBranchParams(**params)
            
            # Call operation
            result = repositories.create_branch(branch_params)
            
            logger.debug(f"Branch created: {branch_params.branch}")
            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 model defining the input schema for the create_branch tool, inheriting from RepositoryRef (owner/repo) and adding branch and from_branch fields with validation.
    class CreateBranchParams(RepositoryRef):
        """Parameters for creating a branch."""
    
        model_config = ConfigDict(strict=True)
        
        branch: str = Field(..., description="Name for new branch")
        from_branch: Optional[str] = Field(
            None, description="Source branch (defaults to repo default)"
        )
    
        @field_validator('branch')
        @classmethod
        def validate_branch(cls, v):
            """Validate that branch is not empty."""
            if not v.strip():
                raise ValueError("branch cannot be empty")
            return v
  • Registers the create_branch tool (imported from tools.py) with the MCP server using 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
    ])
  • Internal helper function that implements the branch creation logic using PyGithub API: gets source ref SHA and creates new git ref.
    def create_branch(params: CreateBranchParams) -> Dict[str, Any]:
        """Create a new branch in a repository.
    
        Args:
            params: Parameters for creating a branch
    
        Returns:
            Branch data in our schema
    
        Raises:
            GitHubError: If branch creation fails
        """
        logger.debug(f"Creating branch {params.branch} in {params.owner}/{params.repo}")
        try:
            client = GitHubClient.get_instance()
            repository = client.get_repo(f"{params.owner}/{params.repo}")
            
            # Get source branch to use as base
            if params.from_branch:
                # Use specified source branch
                source_branch = params.from_branch
            else:
                # Use repository default branch
                source_branch = repository.default_branch
            
            # Get the SHA of the latest commit on the source branch
            source_ref = repository.get_git_ref(f"heads/{source_branch}")
            sha = source_ref.object.sha
            
            # Create the new branch
            new_branch = repository.create_git_ref(f"refs/heads/{params.branch}", sha)
            
            logger.debug(f"Branch created successfully: {params.branch}")
            return {
                "name": params.branch,
                "sha": new_branch.object.sha,
                "url": new_branch.url
            }
        except GithubException as e:
            logger.error(f"GitHub exception when creating branch: {str(e)}")
            raise client._handle_github_exception(e, resource_hint="git_ref")

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