Skip to main content
Glama
AstroMined

PyGithub MCP Server

by AstroMined

create_repository

Create a new GitHub repository with customizable settings including name, description, privacy options, and README initialization through the PyGithub MCP Server.

Instructions

Create a new GitHub repository.

Args:
    params: Dictionary with repository creation parameters
        - name: Repository name
        - description: Repository description (optional)
        - private: Whether the repository should be private (optional)
        - auto_init: Initialize repository with README (optional)

Returns:
    MCP response with created repository details

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paramsYes

Implementation Reference

  • MCP tool handler for create_repository. Validates input parameters using CreateRepositoryParams, delegates to repositories.create_repository operation, handles errors, and formats MCP response.
    @tool()
    def create_repository(params: Dict) -> Dict:
        """Create a new GitHub repository.
    
        Args:
            params: Dictionary with repository creation parameters
                - name: Repository name
                - description: Repository description (optional)
                - private: Whether the repository should be private (optional)
                - auto_init: Initialize repository with README (optional)
    
        Returns:
            MCP response with created repository details
        """
        try:
            logger.debug(f"create_repository called with params: {params}")
            # Convert dict to Pydantic model
            repo_params = CreateRepositoryParams(**params)
            
            # Call operation
            result = repositories.create_repository(repo_params)
            
            logger.debug(f"Got result: {result}")
            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 input schema for create_repository tool with validation for repository name, description, private flag, and auto_init.
    class CreateRepositoryParams(BaseModel):
        """Parameters for creating a new repository."""
    
        model_config = ConfigDict(strict=True)
        
        name: str = Field(..., description="Repository name")
        description: Optional[str] = Field(None, description="Repository description")
        private: Optional[bool] = Field(None, description="Whether repo should be private")
        auto_init: Optional[bool] = Field(
            None, description="Initialize repository with README"
        )
    
        @field_validator('name')
        @classmethod
        def validate_name(cls, v):
            """Validate that name is not empty."""
            if not v.strip():
                raise ValueError("name cannot be empty")
            return v
  • Registers the create_repository tool (along with other repository tools) 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
    ])
  • Core helper function implementing the GitHub API call to create a repository using PyGitHub, handles parameters, converts result to internal schema, and manages errors.
    def create_repository(params: CreateRepositoryParams) -> Dict[str, Any]:
        """Create a new repository.
    
        Args:
            params: Parameters for creating a repository
    
        Returns:
            Repository data in our schema
    
        Raises:
            GitHubError: If repository creation fails
        """
        logger.debug(f"Creating repository: {params.name}")
        try:
            client = GitHubClient.get_instance()
            github = client.github
            
            # Build kwargs from Pydantic model
            kwargs = {
                "name": params.name,
            }
            
            # Add optional parameters only if provided
            if params.description:
                kwargs["description"] = params.description
            if params.private is not None:
                kwargs["private"] = params.private
            if params.auto_init is not None:
                kwargs["auto_init"] = params.auto_init
            
            # Create repository
            repository = github.get_user().create_repo(**kwargs)
            logger.debug(f"Repository created successfully: {repository.full_name}")
            return convert_repository(repository)
        except GithubException as e:
            logger.error(f"GitHub exception when creating repository: {str(e)}")
            raise client._handle_github_exception(e, resource_hint="repository")

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