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
        ])

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