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")
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It states it 'creates' a new branch, implying a mutation, but doesn't cover permissions needed, whether it's idempotent, error conditions, or rate limits. The mention of 'MCP response with branch creation result' is vague and doesn't explain what the result contains.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections for Args and Returns, and sentences are direct without unnecessary fluff. It could be slightly more concise by integrating the parameter list more seamlessly, but overall it's efficient.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of a GitHub branch creation tool with no annotations, no output schema, and nested parameters, the description is incomplete. It lacks details on authentication, error handling, return values, and how it fits with sibling tools, making it insufficient for reliable agent use.

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?

The description lists specific parameters (owner, repo, branch, from_branch) with brief explanations, which adds meaningful context beyond the input schema's generic 'params' object with 0% coverage. However, it doesn't detail data types, constraints, or examples, leaving gaps in understanding.

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

Purpose4/5

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

The description clearly states the verb 'Create' and resource 'new branch in a GitHub repository', making the purpose unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'create_repository' or 'fork_repository' beyond the different resource type, which keeps it from a perfect score.

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 provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., repository access), when not to use it, or how it relates to sibling tools like 'fork_repository' or 'create_repository' for similar creation tasks.

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/AstroMined/pygithub-mcp-server'

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