create_branch
Create a new branch in a GitHub repository using specified parameters such as owner, repo, and branch name, with an 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
| Name | Required | Description | Default |
|---|---|---|---|
| params | Yes |
Implementation Reference
- MCP tool handler for 'create_branch': decorates with @tool(), validates params using CreateBranchParams schema, calls repositories.create_branch operation, handles errors, and returns formatted MCP 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 schema CreateBranchParams for input validation, extending RepositoryRef with branch and from_branch fields.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
- src/pygithub_mcp_server/tools/repositories/__init__.py:9-39 (registration)Registration of repository tools including create_branch via register_tools in the repositories tools module.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 operation function create_branch that interacts with GitHub API to create a new branch from source branch or default.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")