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

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the action ('Create') but fails to mention critical details like required permissions, rate limits, or whether the operation is idempotent. This leaves significant gaps for a mutation tool.

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, making it easy to parse. It is front-loaded with the core purpose, though the Returns section could be more informative given the lack of output schema.

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 creating a repository (a mutation with no annotations and no output schema), the description is incomplete. It lacks details on authentication, error handling, and the structure of returned details, leaving the agent with insufficient context for reliable use.

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

Parameters4/5

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

The schema description coverage is 0%, so the description must compensate. It effectively documents the nested parameters (name, description, private, auto_init) within 'params', adding meaningful semantics beyond the generic schema. However, it does not specify data types or constraints.

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 specific action ('Create') and resource ('a new GitHub repository'), distinguishing it from siblings like 'fork_repository' or 'search_repositories'. It directly answers what the tool does without ambiguity.

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?

No guidance is provided on when to use this tool versus alternatives like 'fork_repository' or 'get_repository'. The description lacks context about prerequisites, such as authentication or permissions, and does not mention when not to use it.

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