Skip to main content
Glama
AstroMined

PyGithub MCP Server

by AstroMined

fork_repository

Create a copy of a GitHub repository to modify code independently or contribute changes. Specify repository owner, name, and optional organization for the fork.

Instructions

Fork an existing GitHub repository.

Args:
    params: Dictionary with fork parameters
        - owner: Repository owner (username or organization)
        - repo: Repository name
        - organization: Organization to fork to (optional)

Returns:
    MCP response with forked repository details

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paramsYes

Implementation Reference

  • The MCP tool handler function for 'fork_repository'. It processes incoming params, validates using ForkRepositoryParams, calls the operations.fork_repository, and formats the MCP response.
    @tool()
    def fork_repository(params: Dict) -> Dict:
        """Fork an existing GitHub repository.
    
        Args:
            params: Dictionary with fork parameters
                - owner: Repository owner (username or organization)
                - repo: Repository name
                - organization: Organization to fork to (optional)
    
        Returns:
            MCP response with forked repository details
        """
        try:
            logger.debug(f"fork_repository called with params: {params}")
            # Convert dict to Pydantic model
            fork_params = ForkRepositoryParams(**params)
            
            # Call operation
            result = repositories.fork_repository(fork_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
            }
  • Core implementation of the fork_repository logic using PyGitHub client to call repository.create_fork() and convert result.
    def fork_repository(params: ForkRepositoryParams) -> Dict[str, Any]:
        """Fork a repository.
    
        Args:
            params: Parameters for forking a repository
    
        Returns:
            Forked repository data in our schema
    
        Raises:
            GitHubError: If repository forking fails
        """
        logger.debug(f"Forking repository: {params.owner}/{params.repo}")
        try:
            client = GitHubClient.get_instance()
            repository = client.get_repo(f"{params.owner}/{params.repo}")
            
            # Build kwargs from Pydantic model
            kwargs = {}
            if params.organization:
                kwargs["organization"] = params.organization
            
            # Fork repository
            forked_repo = repository.create_fork(**kwargs)
            logger.debug(f"Repository forked successfully: {forked_repo.full_name}")
            return convert_repository(forked_repo)
        except GithubException as e:
            logger.error(f"GitHub exception when forking repository: {str(e)}")
            raise client._handle_github_exception(e, resource_hint="repository")
  • Pydantic schema model ForkRepositoryParams used for input validation, inherits from RepositoryRef (owner, repo).
    class ForkRepositoryParams(RepositoryRef):
        """Parameters for forking a repository."""
    
        model_config = ConfigDict(strict=True)
        
        organization: Optional[str] = Field(
            None, description="Organization to fork to (defaults to user account)"
        )
  • Registration of the fork_repository tool (imported from .tools) into the MCP server via register_tools.
    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
        ])
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 ('Fork') but lacks critical details: it doesn't specify if this requires GitHub authentication, what permissions are needed, whether it's a destructive or read-only operation, or any rate limits. For a mutation tool with zero annotation coverage, this is a significant gap in transparency.

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 and appropriately sized. It starts with a clear purpose statement, followed by 'Args' and 'Returns' sections. Every sentence adds value, with no wasted words. It could be slightly more concise by integrating the parameter details 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 (a mutation tool forking repositories), lack of annotations, no output schema, and low schema coverage, the description is incomplete. It doesn't explain return values in detail (beyond 'forked repository details'), authentication requirements, error conditions, or how it differs from sibling tools. For a tool with significant contextual needs, this falls short.

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 schema description coverage is 0%, so the description must compensate. It lists three parameters (owner, repo, organization) with brief explanations, adding meaning beyond the schema's generic 'params' object. However, it doesn't cover all aspects (e.g., data types, constraints, optional vs. required status beyond 'optional' for organization), leaving some ambiguity. This partial compensation justifies a baseline score.

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 tool's purpose: 'Fork an existing GitHub repository.' It specifies the verb ('Fork') and resource ('GitHub repository'), making the action clear. However, it doesn't explicitly differentiate from sibling tools like 'create_repository' or 'search_repositories', which is why it doesn't earn a 5.

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., authentication needs), when to choose forking over cloning or creating a new repository, or any exclusions. This leaves the agent without context for tool selection among siblings.

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